# DhanHQ API Documentation — Full Export

> Generated on 2026-07-16T11:23:04.589Z
> Total documents: 151

---

---

## 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| 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`. 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| 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`. 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 order status ([see Annexure](/api/v2/guides/annexure#order-status)) Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### 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 and Multi Order

Conditional and Multi Order

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 Order |
| POST | `/alerts/multi/orders` | Place Multi Order |
| PUT | `/alerts/orders/{alertId}` | Modify Conditional Order |
| DELETE | `/alerts/orders/{alertId}` | Delete Conditional Order |
| GET | `/alerts/orders/{alertId}` | Get Conditional Order by ID |
| GET | `/alerts/orders` | Get All Conditional Orders |

> **note:** - Conditional Orders 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:** 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 | boolean | 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`. Default: `INTRADAY`. |
| exchangeSegment | enum | No | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| 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`. 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 Order

`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 alert status ([see Annexure](/api/v2/guides/annexure#status)) 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 that enables you to build trading and investment services, applications, and strategies.

It provides a set of REST-like APIs that integrate directly with our trading platform. With DhanHQ APIs, you can execute and modify orders in real time, manage portfolios, access live market data, and more through a fast and reliable API collection.

The platform uses resource-based URLs and supports JSON as well as form-encoded requests. Responses are returned in JSON format using standard HTTP response codes, verbs, and authentication methods.


  
  - [DhanHQ Python Client](https://github.com/dhan-oss/DhanHQ-py)


## Structure


#### REST

All **GET** and **DELETE** request parameters go as query parameters, and **POST** and **PUT** parameters as form-encoded. User has to input an access token in the header for every request.

```bash
curl --request POST \
  --url https://api.dhan.co/v2/ \
  --header 'Content-Type: application/json' \
  --header 'access-token: <your-access-token>' \
  --data '{Request JSON}'
```

#### Python

Install Python Package directly using following command in command line.

```bash
pip install dhanhq
```
This installs entire DhanHQ Python Client along with the required packages. Now, you can start using DhanHQ Client with your Python script.

You can now import 'dhanhq' module and connect to your Dhan account.

```bash
from dhanhq import dhanhq

dhan = dhanhq("client_id","access_token")
```


## 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`, `MCX`, `ALL`. Default: `NSE`. |
| segment | enum | Yes | Trading segment Values: `EQ`, `COMM`, `FNO`. Default: `EQ`. |
| bulk | boolean | No | Whether to generate form for bulk EDIS |


### 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 Orders

`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 Order 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 45 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 45 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+10, ATM-10, 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`, `30`, `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 | 1=Near, 2=Next, 3=Far Values: `1`, `2`, `3`. Default: `1`. |
| strike | string | No | ATM, ATM+10, 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, 30, 60 minute intervals).

Retrieve Open, High, Low, Close, OI & Volume of 1, 5, 15, 30 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`, `30`, `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`. |
| 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`. |
| 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`. |
| 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`. |
| 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 order status ([see Annexure](/api/v2/guides/annexure#order-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`. |
| 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`. |
| 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`. |
| 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>"
```

---

## Global Stocks

Global Stocks

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Place Order](/api/v2/global-stocks/place-order) | Place a buy or sell order for a US stock using the selected order type, quantity, and price details. |
| PUT | [Modify Order](/api/v2/global-stocks/modify-order) | Modify an existing pending US stock order by submitting updated order details for the given order ID. |
| GET | [Get Order by ID](/api/v2/global-stocks/get-order-by-id) | Retrieve the latest order details and status for a specific US stock order using its order ID. |
| DELETE | [Cancel Order](/api/v2/global-stocks/cancel-order) | Cancel an existing pending US stock order using its order ID. |
| GET | [Get Order Book](/api/v2/global-stocks/get-order-book) | Retrieve the current trading day's US stock order book for the authenticated user. |
| POST | [Order Estimator](/api/v2/global-stocks/order-estimator) | Estimate the applicable charges for a US stock order before submitting it. |
| POST | [Margin Calculator](/api/v2/global-stocks/margin-calculator) | Calculate the margin required for a US stock order before submitting it. |
| GET | [Get Past Trades](/api/v2/global-stocks/get-past-trades) | Retrieve the current trading day's executed US stock trades for the authenticated user. |
| GET | [Get Past Trades by Security Id](/api/v2/global-stocks/get-past-trades-by-scrip) | Retrieve executed US stock trades for the authenticated user filtered by a specific security ID. |
| GET | [Get Market Status](/api/v2/global-stocks/get-market-status) | Retrieve the current trading status and session timing for the US stock market. |
| WebSocket | [Global Stocks Live Feed](/api/v2/global-stocks/data-apis/broadcast-websocket) | Subscribe to real-time Trade and OHLC packets for Global Stocks. |
| GET | [Get Holdings](/api/v2/global-stocks/get-holdings) | Retrieve the authenticated user's current US stock holdings and holding-level details. |
| GET | [Get Fund Limit](/api/v2/global-stocks/get-fund-limit) | Retrieve the authenticated user's fund limit details for US stock trading. |

---

## Global Stocks Live Feed

Real-time Global Stocks market data over WebSocket.

The Global Stocks Live Feed streams real-time market data for supported international stocks. Client applications send JSON subscription requests, while the server sends compact binary market-data packets over WebSocket.

- Protocol: WebSocket, binary frames (opcode `2`)
- Client request format: JSON
- Server response format: binary WebSocket frames
- Byte order: little-endian for all multi-byte numbers
- Supported exchange segment: `INX_EQ`

## Establishing Connection

Open a WebSocket connection to:

```text
wss://<host>/?clientId=<clientId>&token=<authToken>&authType=<type>&version=2
```

For the Dhan-hosted Global Stocks feed, use:

```text
wss://global-stocks-api-feed.dhan.co/?clientId=<your-client-id>&token=<your-access-token>&authType=<type>&version=2
```

Self-hosted deployments typically expose the feed over `ws` on port `7075`.

| Parameter | Required | Description |
|-----------|----------|-------------|
| `clientId` | Yes | Dhan Client ID. For partner authentication, pass the Partner ID. |
| `token` | Yes | Access token. For partner authentication, pass the secret key. |
| `authType` | Yes | `1` for Partner's Client, `2` for Self, `3` for Partner. |
| `version` | Yes | Must be `2`. |

Connection handling:

- On successful authentication, the connection remains open for subscriptions.
- On authentication failure, the server sends an Error packet and closes the connection.
- A maximum of 5 concurrent WebSocket connections are allowed per `clientId`. If a 6th connection is opened, the oldest connection is disconnected with error code `805`.
- More than 10 repeated invalid connection attempts may temporarily block the source IP.
- If the WebSocket upgrade fails, inspect the HTTP status and response body. `EOF` or a missing HTTP response indicates that the server closed the TLS/WebSocket handshake before accepting the connection. `400 Bad Request` indicates that the query parameters were received but rejected. Stop the connection flow and recheck `clientId`, `token`, `authType`, and `version` before sending any request.

## Request Messages

All request messages are JSON. Each request contains a `requestCode`.

| requestCode | Action |
|-------------|--------|
| `12` | Disconnect |
| `15` | Subscribe Trade |
| `16` | Unsubscribe Trade |
| `17` | Subscribe OHLC |
| `18` | Unsubscribe OHLC |

### Subscribe or Unsubscribe

Use this request structure for request codes `15`, `16`, `17`, and `18`.

```json
{
  "requestCode": 15,
  "instrumentCount": 2,
  "instrumentList": [
    { "exchangeSegment": "INX_EQ", "securityId": "1234" },
    { "exchangeSegment": "INX_EQ", "securityId": "5678" }
  ]
}
```

| Field | Type | Description |
|-------|------|-------------|
| `requestCode` | int | Request code for subscribing or unsubscribing Trade or OHLC data. |
| `instrumentCount` | int | Number of instruments in `instrumentList`. Maximum 100 instruments per request. |
| `instrumentList` | array | List of instruments to subscribe or unsubscribe. |
| `instrumentList[].exchangeSegment` | string | Currently supported value: `INX_EQ`. |
| `instrumentList[].securityId` | string | Security ID of the instrument. |

Each connection supports up to 5000 total subscriptions. Trade and OHLC subscriptions are maintained independently for each instrument.

To receive both Trade and OHLC for the same instrument, send separate subscribe requests for `requestCode` `15` and `17`.

### Disconnect

```json
{ "requestCode": 12 }
```

## Keeping Connection Alive

The server sends WebSocket Ping frames approximately every 10 seconds. Most WebSocket libraries automatically reply with Pong frames.

If 4 consecutive Ping frames are not answered, the server closes the connection.

If the connection closes abnormally, for example with close `1006` or `unexpected EOF`, reconnect and re-subscribe.

## Binary Response

Binary messages consist of sequences of bytes that represent the data. Binary messages require parsing to extract the relevant information.

All responses from Global Stocks Live Feed consist of [Response Header](#response-header) and Payload. Header for every response message remains the same with different `MsgCode`, while the payload can be different.

The data on Global Stocks Live Feed is sent in little-endian byte order. Structs are packed with no alignment padding.

A single WebSocket message can contain one packet or multiple packets concatenated together. Parse each message in a loop until the full binary buffer is consumed.

### Response Header

The response header message is of 11 bytes and remains part of every response message. The message structure is given below.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0` | uint8 | 1 | Exchange segment. `14` represents `INX_EQ`. |
| `1-4` | int32 | 4 | Security ID. |
| `5-8` | int32 | 4 | Duplicate of Security ID. |
| `9` | uint8 | 1 | Message length of the entire packet. |
| `10` | uint8 | 1 | Message code. |

`MsgCode` is byte `10` of the header. Reading byte `0` as the message code will read the exchange segment instead.

### Message Codes

| MsgCode | Packet | Total Size |
|---------|--------|------------|
| `1` | Trade | 27 bytes |
| `3` | OHLC | 27 bytes |
| `29` | Market Status | 18 bytes |
| `32` | Previous Close | 15 bytes |
| `33` | Circuit Limit | 19 bytes |
| `36` | 52-Week High/Low | 19 bytes |
| `50` | Error | 13 bytes |

### Trade Packet

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0-10` | [ ] byte | 11 | [Response Header](#response-header) with `MsgCode = 1`. |
| `11-14` | float32 | 4 | LTP - Last Traded Price. |
| `15-18` | int32 | 4 | Volume. |
| `19-22` | int32 | 4 | LTT - Last Trade Time, in Unix epoch seconds for the feed timestamp. |
| `23-26` | int32 | 4 | LUT - Last Update Time, in Unix epoch seconds. |

### OHLC Packet

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0-10` | [ ] byte | 11 | [Response Header](#response-header) with `MsgCode = 3`. |
| `11-14` | float32 | 4 | FOpen - Open. |
| `15-18` | float32 | 4 | FClose - Close. |
| `19-22` | float32 | 4 | FHigh - High. |
| `23-26` | float32 | 4 | FLow - Low. |

### Previous Close Packet

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0-10` | [ ] byte | 11 | [Response Header](#response-header) with `MsgCode = 32`. |
| `11-14` | float32 | 4 | PClose - Previous Close. |

### Circuit Limit Packet

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0-10` | [ ] byte | 11 | [Response Header](#response-header) with `MsgCode = 33`. |
| `11-14` | float32 | 4 | UCkt - Upper Circuit. |
| `15-18` | float32 | 4 | LCkt - Lower Circuit. |

### 52-Week High/Low Packet

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0-10` | [ ] byte | 11 | [Response Header](#response-header) with `MsgCode = 36`. |
| `11-14` | float32 | 4 | F52WKHIGH - 52-Week High. |
| `15-18` | float32 | 4 | F52WKLOW - 52-Week Low. |

### Market Status Packet

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0-10` | [ ] byte | 11 | [Response Header](#response-header) with `MsgCode = 29`. |
| `11-13` | uint8[3] | 3 | MarketType. |
| `14-17` | int32 | 4 | MarketStatus. |

## Feed Disconnect

In case of authentication failure or server-side disconnection, you will receive an Error packet with disconnection reason code. After sending the Error packet, the server closes the connection.

Error packets use `MsgCode = 50`, total length 13 bytes, and are sent as standalone binary messages. Error packets are not batched with market-data packets. Error packets use the same 11-byte header as market-data packets, followed by a 2-byte error code.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| `0` | uint8 | 1 | ExchSeg. `0` when not set. |
| `1-4` | int32 | 4 | ScripId. `0` when not set. |
| `5-8` | int32 | 4 | ScripId2. `0` when not set. |
| `9` | uint8 | 1 | MsgLength. `13`. |
| `10` | uint8 | 1 | MsgCode. `50`. |
| `11-12` | int16 | 2 | Disconnection message code. |

| ErrCode | Description |
|---------|-------------|
| `805` | Connection limit exceeded. |
| `806` | Payment not done for broadcast. |
| `807` | Token expired. |
| `808` | Authentication failure. |
| `809` | Invalid token. |

## First Tick Snapshot

Subscription flow:

- Subscribe Trade, `requestCode = 15`: the server sends, per instrument and in order, `Trade(1)`, `PClose(32)`, `CircuitLimit(33)`, and `52WK(36)`, followed by live `Trade(1)` updates.
- Subscribe OHLC, `requestCode = 17`: the server sends an `OHLC(3)` snapshot, followed by live `OHLC(3)` updates.
- `PClose(32)`, `CircuitLimit(33)`, and `52WK(36)` are sent once on subscription. They are not part of every live Trade update.
- `MarketStatus(29)` is pushed on market open, close, and similar session state changes.
- Keep-alive: the server sends Ping frames about every 10 seconds. The client must send Pong frames; 4 missed Pong responses disconnect the connection.

For OHLC and reference packets:

- If a reference value is unavailable, for example before market open or before the feed has populated the instrument, the server may send a zero-filled Circuit Limit or 52-Week packet with `ScripId = 0` and `0.00` values.
- Treat zero-filled reference packets as valid "no data yet" packets. Once values are available, the same packet types are sent with the instrument's `ScripId` and populated values.

## Packed Struct Reference

The following structures map to the wire format. Read all multi-byte values as little-endian and avoid alignment padding when mapping bytes directly.

```text
Header       { uint8 exchSeg; int32 scripId; int32 scripId2; uint8 msgLength; uint8 msgCode }             // 11 bytes
Trade        { Header; float32 ltp; int32 volume; int32 ltt; int32 lut }           // 27 bytes
Ohlc         { Header; float32 fOpen; float32 fClose; float32 fHigh; float32 fLow } // 27 bytes
PClose       { Header; float32 pClose }                                             // 15 bytes
CircuitLimit { Header; float32 uCkt; float32 lCkt }                                 // 19 bytes
Week52       { Header; float32 high; float32 low }                                  // 19 bytes
MarketStatus { Header; byte mktType[3]; int32 mktStatus }                           // 18 bytes
ErrorPacket  { Header; int16 errCode }                                              // 13 bytes
```

## Parsing Example

```python
SIZES = {1: 27, 3: 27, 29: 18, 32: 15, 33: 19, 36: 19, 50: 13}

def on_binary_message(buf):
    offset = 0
    while offset < len(buf):
        msg_length = buf[offset + 9]
        msg_code = buf[offset + 10]
        size = msg_length or SIZES.get(msg_code, 0)

        if size == 0 or offset + size > len(buf):
            break

        packet = buf[offset:offset + size]
        dispatch(msg_code, packet)
        offset += size
```

Parsing and client behavior notes:

- Buffer advancement:
  - Use `MsgLength` as the primary value for advancing through the buffer.
  - Use the fixed `SIZES` table as a fallback and sanity check.
  - Guard against `0` so the parser does not loop forever on malformed data.
- Read-loop handling:
  - Keep the read loop active for the lifetime of the connection.
  - In Go, a `break` inside a `switch` exits only the `switch`, not the outer parse loop. Use an outer-loop break when stopping on malformed data or an error packet.
  - If another foreground service keeps the process alive, handle its startup errors explicitly so a bind failure does not stop the feed reader unexpectedly.
- Field values:
  - `LTT` and `LUT` are seconds-based epoch values. Multiply by `1000` when your application needs millisecond epoch timestamps.
  - If a time decodes near 1970, the field was likely not populated in that packet yet.

## Quick Reference

| Item | Value |
|------|-------|
| Global feed host | `global-stocks-api-feed.dhan.co` over `wss` |
| Self-hosted port | `7075` over `ws` |
| Frame type | Binary WebSocket frame, opcode `2` |
| Request format | JSON |
| Byte order | Little-endian |
| Supported exchange segment | `INX_EQ`, numeric value `14` |
| Max instruments per request | `100` |
| Max subscriptions per connection | `5000` |
| Max connections per client | `5` |
| Heartbeat | Ping about every 10 seconds; disconnect after 4 missed Pongs |
| Batching | Multiple packets can be concatenated in one WebSocket message |

## Sample Decoded Packets

```text
Header: ExchSeg=14 ScripId=10008660 ScripId2=10008660 MsgLength=27 MsgCode=1
Trade   | ScripId=10008660 LTP=21.39 Vol=33064007 LTT=1466625591 LUT=1782158394

Header: ExchSeg=14 ScripId=10008660 ScripId2=10008660 MsgLength=15 MsgCode=32
PClose  | ScripId=10008660 PClose=21.36

Header: ExchSeg=14 ScripId=10008660 ScripId2=10008660 MsgLength=19 MsgCode=33
CktLmt  | ScripId=10008660 UCkt=27.77 LCkt=14.95

Header: ExchSeg=14 ScripId=10008660 ScripId2=10008660 MsgLength=19 MsgCode=36
52Week  | ScripId=10008660 High=58.15 Low=10.30
```

---

## Cancel Order

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

Cancel an existing pending US stock order using its order ID.




### Path Parameters

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


### 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`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | order cancelled |


### Example Request

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

---

## Data APIs

Global Stocks Data APIs

provide real-time market data for supported international stocks.

| Type | Endpoint | Description |
|------|----------|-------------|
| WebSocket | [Global Stocks Live Feed](/api/v2/global-stocks/data-apis/broadcast-websocket) | Subscribe to real-time Trade and OHLC packets for Global Stocks. |

---

## Funds & Margin

Global Stocks Funds & Margin

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/globalstocks/transEstimate` | Estimate the applicable charges for a US stock order before submitting it. |
| GET | `/globalstocks/fundlimit` | Retrieve the authenticated user's fund limit details for US stock trading. |
| POST | `/globalstocks/margincalculator` | Calculate the margin required for a US stock order before submitting it. |

---

## Get Fund Limit

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

Retrieve the authenticated user's fund limit details for US stock trading.




### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| availableCash | float | No | Available cash |
| cashOnAccount | float | No | Cash on account |
| actualCash | float | No | Actual cash |
| settledCash | float | No | Settled cash |
| unsettledCash | float | No | Unsettled cash |
| marginUtilized | float | No | Margin utilized |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | fund limit details |


### Example Request

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

---

## Get Holdings

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

Retrieve the authenticated user's current US stock holdings and holding-level details.




### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| tradingSymbol | string | No | Trading symbol |
| displayName | string | No | Display name |
| securityId | string | No | Exchange standard ID for the scrip |
| exchange | string | No | Exchange |
| quantity | float | No | Holding quantity |
| avgCostPrice | float | No | Average cost price in USD |
| costValue | float | No | Cost value |
| currentValue | float | No | Current value |
| gainValue | float | No | Gain value |
| ltp | float | No | Last traded price in USD |
| prevClose | float | No | Previous close price in USD |
| longTermFlag | string | No | Long-term holding flag |
| lastUpdated | string | No | Last updated time |


### Status Codes

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


### Example Request

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

---

## Get Market Status

`GET` https://api.dhan.co/v2/globalstocks/marketstatus

Retrieve the current trading status and session timing for the US stock market.




### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| marketCloseTime | string | No | Market close time |
| marketOpenTime | string | No | Market open time |
| holidayFlag | boolean | No | Holiday flag |
| status | string | No | Market status - open/closed |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | market status |


### Example Request

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

---

## Get Order Book

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

Retrieve the current trading day's US stock order book for the authenticated user.




### 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 |
| transactionType | string | No | The trading side |
| exchangeSegment | string | No | Exchange segment |
| productType | string | No | Product type |
| orderType | enum string | No | Order Type Values: `MARKET`, `LIMIT`, `STOP_LOSS`, `STOP_LOSS_MARKET`, `AMOUNT`. |
| validity | string | No | Order validity |
| tradingSymbol | string | No | Trading symbol |
| displayName | string | No | Display name |
| securityId | string | No | Exchange standard ID for the scrip |
| quantity | float | No | Number of shares for the order |
| remainingQuantity | float | No | Quantity pending to be traded |
| tradedQty | float | No | Quantity traded |
| price | float | No | Order price in USD. Use 0 for market orders. |
| triggerPrice | float | No | Price in USD at which order is triggered |
| avgTradedPrice | float | No | Average traded price in USD |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |
| createTime | string | No | Time at which the order is created |
| exchangeTime | string | No | Time at which order reached the exchange |
| updateTime | string | No | Time at which the last activity happened |
| omsErrorCode | string | No | Error code if the order is rejected or failed |
| omsErrorDescription | string | No | Error description if the order is rejected or failed |
| afterMarketOrder | boolean | No | Whether the order is an after-market order |
| amount | float | No | Amount for AMOUNT type orders |
| lotSize | integer | No | Lot size |
| fractionalFlag | boolean | No | Whether the order is fractional |
| legName | string | No | Leg name for super orders Values: `ENTRY_LEG`, `STOP_LOSS_LEG`, `TARGET_LEG`, `NA`. |
| childOrders | array<object> | No | Child orders |


### Status Codes

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


### Example Request

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

---

## Get Order by ID

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

Retrieve the latest order details and status for a specific US stock order using its 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 |
| 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 |
| transactionType | string | No | The trading side |
| exchangeSegment | string | No | Exchange segment |
| productType | string | No | Product type |
| orderType | enum string | No | Order Type Values: `MARKET`, `LIMIT`, `STOP_LOSS`, `STOP_LOSS_MARKET`, `AMOUNT`. |
| validity | string | No | Order validity |
| tradingSymbol | string | No | Trading symbol |
| displayName | string | No | Display name |
| securityId | string | No | Exchange standard ID for the scrip |
| quantity | float | No | Number of shares for the order |
| remainingQuantity | float | No | Quantity pending to be traded |
| tradedQty | float | No | Quantity traded |
| price | float | No | Order price in USD. Use 0 for market orders. |
| triggerPrice | float | No | Price in USD at which order is triggered |
| avgTradedPrice | float | No | Average traded price in USD |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |
| createTime | string | No | Time at which the order is created |
| exchangeTime | string | No | Time at which order reached the exchange |
| updateTime | string | No | Time at which the last activity happened |
| omsErrorCode | string | No | Error code if the order is rejected or failed |
| omsErrorDescription | string | No | Error description if the order is rejected or failed |
| afterMarketOrder | boolean | No | Whether the order is an after-market order |
| amount | float | No | Amount for AMOUNT type orders |
| lotSize | integer | No | Lot size |
| fractionalFlag | boolean | No | Whether the order is fractional |
| legName | string | No | Leg name for super orders Values: `ENTRY_LEG`, `STOP_LOSS_LEG`, `TARGET_LEG`, `NA`. |
| childOrders | array<object> | No | Child orders |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | order details |


### Example Request

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

---

## Get Past Trades by Security Id

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

Retrieve executed US stock trades for the authenticated user filtered by a specific security ID.




### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| security-id | string | Yes | Exchange standard ID for the scrip |


### 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 |
| transactionType | string | No | Signifies the type of transaction whether it's BUY or SELL |
| exchangeSegment | string | No | Exchange segment |
| productType | string | No | Product type |
| orderType | string | No | Order type |
| tradingSymbol | string | No | Exchange standard trading symbol |
| securityId | string | No | Exchange standard identification for each scrip |
| tradedQuantity | number<float> | No | Number of shares traded (fractional supported) |
| tradedPrice | number<float> | No | Price in USD at which trade executed |
| tradeDate | string | No | Trade date |
| createTime | string | No | Record create date time |
| exchangeTime | string | No | Time at which order reached at exchange end |
| orderStatus | string | No | Trade status |
| brokerage | number<float> | No | Brokerage charges |
| otherCharges | number<float> | No | Other fees |
| tradeValue | number<float> | No | Average trade value |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | trades for security |


### Example Request

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

---

## Get Past Trades

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

Retrieve the current trading day's executed US stock trades for the authenticated user.




### 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 |
| transactionType | string | No | Signifies the type of transaction whether it's BUY or SELL |
| exchangeSegment | string | No | Exchange segment |
| productType | string | No | Product type |
| orderType | string | No | Order type |
| tradingSymbol | string | No | Exchange standard trading symbol |
| securityId | string | No | Exchange standard identification for each scrip |
| tradedQuantity | number<float> | No | Number of shares traded (fractional supported) |
| tradedPrice | number<float> | No | Price in USD at which trade executed |
| tradeDate | string | No | Trade date |
| createTime | string | No | Record create date time |
| exchangeTime | string | No | Time at which order reached at exchange end |
| orderStatus | string | No | Trade status |
| brokerage | number<float> | No | Brokerage charges |
| otherCharges | number<float> | No | Other fees |
| tradeValue | number<float> | No | Average trade value |


### Status Codes

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


### Example Request

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

---

## Margin Calculator

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

Calculate the margin required for a US stock order before submitting it.




### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| securityId | string | Yes | Exchange standard ID for the scrip |
| price | string | Yes | Order price in USD. Use 0 for market orders. |
| quantity | string | Yes | Order quantity |
| transactionType | enum | Yes | The trading side Values: `BUY`, `SELL`. Default: `BUY`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| brokerage | number<float> | No | Brokerage |
| leverage | string | No | Leverage |
| insufficientBal | number<float> | No | Insufficient balance |
| totalMargin | number<float> | No | Total margin required |
| availableBal | number<float> | No | Available balance |


### Status Codes

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


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/globalstocks/margincalculator \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "securityId": "AAPL",
    "price": "180",
    "quantity": "1",
    "transactionType": "BUY"
  }'
```

---

## Modify Order

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

Modify an existing pending US stock order by submitting updated order details for the given order ID.




### 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 | No | User specific identification generated by Dhan |
| orderType | enum | Yes | Order Type Values: `MARKET`, `LIMIT`, `STOP_LOSS`, `STOP_LOSS_MARKET`, `AMOUNT`. Default: `LIMIT`. |
| transactionType | enum | Yes | The trading side Values: `BUY`, `SELL`. Default: `BUY`. |
| securityId | string | Yes | Exchange standard ID for the scrip |
| quantity | float | No | Quantity to be modified |
| price | float | No | Order price in USD. Use 0 for market orders. |
| legName | enum | No | Leg name - ENTRY_LEG, STOP_LOSS_LEG, TARGET_LEG Values: `ENTRY_LEG`, `STOP_LOSS_LEG`, `TARGET_LEG`, `NA`. Default: `NA`. |


### 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`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### Status Codes

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


### Example Request

```bash
curl -X PUT https://api.dhan.co/v2/globalstocks/orders/{order-id} \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "orderType": "LIMIT",
    "transactionType": "BUY",
    "securityId": "AAPL",
    "quantity": 1,
    "price": 180.00
  }'
```

---

## Order Estimator

`POST` https://api.dhan.co/v2/globalstocks/transEstimate

Estimate the applicable charges for a US stock order before submitting it.




### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| securityId | string | Yes | Exchange standard ID for the scrip |
| price | string | Yes | Order price in USD. Use 0 for market orders. |
| quantity | string | Yes | Order quantity |
| transactionType | enum | Yes | The trading side Values: `BUY`, `SELL`. Default: `BUY`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| brokerage | number<float> | No | Brokerage charges |
| orderCharges | number<float> | No | Total order charges |
| exchangeCharges | number<float> | No | Exchange charges |
| turnOverFee | number<float> | No | Turnover fee |
| gstCharges | number<float> | No | GST charges |
| otherCharges | number<float> | No | Other charges |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Transaction estimate |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/globalstocks/transEstimate \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "securityId": "AAPL",
    "price": "180",
    "quantity": "1",
    "transactionType": "BUY"
  }'
```

---

## Orders

Global Stocks Orders

The Global Stocks order management API lets you place a new order, modify or cancel a pending order, and retrieve the order book.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/globalstocks/orders` | Place a buy or sell order for a US stock using the selected order type, quantity, and price details. |
| PUT | `/globalstocks/orders/{order-id}` | Modify an existing pending US stock order by submitting updated order details for the given order ID. |
| DELETE | `/globalstocks/orders/{order-id}` | Cancel an existing pending US stock order using its order ID. |
| GET | `/globalstocks/orders/{order-id}` | Retrieve the latest order details and status for a specific US stock order using its order ID. |
| GET | `/globalstocks/orders` | Retrieve the current trading day's US stock order book for the authenticated user. |

---

## Place Order

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

Place a buy or sell order for a US stock using the selected order type, quantity, and price details.




### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| correlationId | string | No | The user/partner generated id for tracking back (max 30 chars) |
| transactionType | enum | Yes | The trading side Values: `BUY`, `SELL`. Default: `BUY`. |
| orderType | enum | Yes | Order Type Values: `MARKET`, `LIMIT`, `STOP_LOSS`, `STOP_LOSS_MARKET`, `AMOUNT`. Default: `LIMIT`. |
| securityId | string | Yes | Exchange standard ID for each scrip |
| quantity | float | No | Number of shares for the order |
| price | float | No | Order price in USD. Use 0 for market orders. |
| triggerPrice | float | No | Price in USD at which order is triggered (for stop loss orders) |
| stopLossPrice | float | No | Stop loss price in USD |
| targetPrice | float | No | Target price in USD |
| amount | float | No | Amount for AMOUNT type orders |
| afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |


### 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`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### Status Codes

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


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/globalstocks/orders \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "transactionType": "BUY",
    "orderType": "LIMIT",
    "securityId": "AAPL",
    "quantity": 1,
    "price": 180.00
  }'
```

---

## Portfolio & Positions

Global Stocks Portfolio & Positions

The Global Stocks portfolio API lets you retrieve your current holdings.

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/globalstocks/holdings` | Retrieve the authenticated user's current US stock holdings and holding-level details. |

---

## Statements

Global Stocks Statements

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/globalstocks/trades` | Retrieve the current trading day's executed US stock trades for the authenticated user. |
| GET | `/globalstocks/trades/{security-id}` | Retrieve executed US stock trades for the authenticated user filtered by a specific security ID. |

---

## Trader's Control

Global Stocks Trader's Control

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/globalstocks/marketstatus` | Retrieve the current trading status and session timing for the US stock market. |

---

## 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:** 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 | Kill switch status Values: `ACTIVATE`, `DEACTIVATE`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| killSwitchStatus | string | No | Status of Kill Switch Values: `ACTIVATE`, `DEACTIVATE`. |


### 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:** You can fetch upto 1000 instruments in single API request with rate limit of 1 request per second.

---

## Modify Conditional Order

`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)


> **Multi-order:** Create a conditional trigger with up to 15 orders. Start with Order 1 and add additional orders sequentially.


### Path Parameters

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


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | 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 (see Annexure) Values: `TECHNICAL_WITH_VALUE`, `TECHNICAL_WITH_INDICATOR`, `TECHNICAL_WITH_CLOSE`, `PRICE_WITH_VALUE`. 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 (>= 0 characters, <= 20 characters). refer here |
| condition.indicatorName | string | No | Name of the technical indicator (see Annexure) |
| 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 (see Annexure) 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 | The technical indicator to compare against when using TECHNICAL_WITH_INDICATOR (see Annexure) |
| condition.expDate | string | Yes | Expiry date of the conditional trigger (YYYY-MM-DD) |
| condition.frequency | enum | Yes | Evaluation frequency Values: `ONCE`. 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[0].productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. 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") |
| orders[1].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[1].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[1].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[1].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[1].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[1].quantity | int | No | Number of shares for the order |
| orders[1].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[1].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[1].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[1].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[2].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[2].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[2].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[2].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[2].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[2].quantity | int | No | Number of shares for the order |
| orders[2].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[2].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[2].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[2].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[3].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[3].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[3].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[3].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[3].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[3].quantity | int | No | Number of shares for the order |
| orders[3].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[3].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[3].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[3].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[4].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[4].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[4].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[4].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[4].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[4].quantity | int | No | Number of shares for the order |
| orders[4].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[4].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[4].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[4].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[5].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[5].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[5].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[5].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[5].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[5].quantity | int | No | Number of shares for the order |
| orders[5].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[5].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[5].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[5].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[6].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[6].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[6].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[6].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[6].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[6].quantity | int | No | Number of shares for the order |
| orders[6].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[6].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[6].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[6].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[7].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[7].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[7].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[7].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[7].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[7].quantity | int | No | Number of shares for the order |
| orders[7].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[7].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[7].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[7].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[8].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[8].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[8].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[8].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[8].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[8].quantity | int | No | Number of shares for the order |
| orders[8].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[8].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[8].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[8].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[9].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[9].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[9].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[9].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[9].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[9].quantity | int | No | Number of shares for the order |
| orders[9].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[9].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[9].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[9].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[10].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[10].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[10].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[10].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[10].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[10].quantity | int | No | Number of shares for the order |
| orders[10].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[10].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[10].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[10].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[11].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[11].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[11].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[11].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[11].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[11].quantity | int | No | Number of shares for the order |
| orders[11].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[11].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[11].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[11].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[12].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[12].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[12].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[12].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[12].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[12].quantity | int | No | Number of shares for the order |
| orders[12].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[12].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[12].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[12].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[13].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[13].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[13].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[13].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[13].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[13].quantity | int | No | Number of shares for the order |
| orders[13].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[13].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[13].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[13].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[14].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[14].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[14].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[14].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[14].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[14].quantity | int | No | Number of shares for the order |
| orders[14].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[14].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[14].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[14].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 alert status ([see Annexure](/api/v2/guides/annexure#status)) 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`. |
| 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`. |
| legName | enum | No | Leg name for Super Order modification Values: `ENTRY_LEG`, `STOP_LOSS_LEG`, `TARGET_LEG`, `NA`. Default: `NA`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| orderId | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated order status ([see Annexure](/api/v2/guides/annexure#order-status)) Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### 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 order status ([see Annexure](/api/v2/guides/annexure#order-status)) Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### 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:** 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 Order

`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)


> **Multi-order:** Create a conditional trigger with up to 15 orders. Start with Order 1 and add additional orders sequentially.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| condition.comparisonType | enum | Yes | Type of comparison for the condition (see Annexure) Values: `TECHNICAL_WITH_VALUE`, `TECHNICAL_WITH_INDICATOR`, `TECHNICAL_WITH_CLOSE`, `PRICE_WITH_VALUE`. 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 (>= 0 characters, <= 20 characters). refer here |
| condition.indicatorName | string | No | Name of the technical indicator (see Annexure) |
| 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 (see Annexure) 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 | The technical indicator to compare against when using TECHNICAL_WITH_INDICATOR (see Annexure) |
| condition.expDate | string | Yes | Expiry date of the conditional trigger (YYYY-MM-DD) |
| condition.frequency | enum | Yes | Evaluation frequency Values: `ONCE`. 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[0].productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. 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") |
| orders[1].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[1].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[1].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[1].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[1].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[1].quantity | int | No | Number of shares for the order |
| orders[1].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[1].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[1].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[1].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[2].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[2].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[2].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[2].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[2].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[2].quantity | int | No | Number of shares for the order |
| orders[2].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[2].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[2].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[2].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[3].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[3].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[3].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[3].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[3].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[3].quantity | int | No | Number of shares for the order |
| orders[3].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[3].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[3].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[3].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[4].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[4].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[4].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[4].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[4].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[4].quantity | int | No | Number of shares for the order |
| orders[4].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[4].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[4].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[4].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[5].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[5].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[5].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[5].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[5].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[5].quantity | int | No | Number of shares for the order |
| orders[5].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[5].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[5].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[5].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[6].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[6].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[6].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[6].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[6].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[6].quantity | int | No | Number of shares for the order |
| orders[6].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[6].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[6].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[6].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[7].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[7].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[7].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[7].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[7].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[7].quantity | int | No | Number of shares for the order |
| orders[7].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[7].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[7].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[7].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[8].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[8].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[8].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[8].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[8].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[8].quantity | int | No | Number of shares for the order |
| orders[8].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[8].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[8].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[8].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[9].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[9].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[9].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[9].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[9].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[9].quantity | int | No | Number of shares for the order |
| orders[9].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[9].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[9].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[9].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[10].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[10].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[10].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[10].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[10].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[10].quantity | int | No | Number of shares for the order |
| orders[10].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[10].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[10].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[10].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[11].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[11].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[11].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[11].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[11].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[11].quantity | int | No | Number of shares for the order |
| orders[11].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[11].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[11].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[11].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[12].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[12].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[12].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[12].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[12].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[12].quantity | int | No | Number of shares for the order |
| orders[12].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[12].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[12].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[12].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[13].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[13].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[13].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[13].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[13].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[13].quantity | int | No | Number of shares for the order |
| orders[13].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[13].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[13].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[13].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |
| orders[14].transactionType | enum | No | The trading side of transaction Values: `BUY`, `SELL`. |
| orders[14].exchangeSegment | enum | No | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[14].productType | enum | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[14].orderType | enum | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[14].securityId | string | No | Exchange standard ID for each scrip. refer here |
| orders[14].quantity | int | No | Number of shares for the order |
| orders[14].validity | enum | No | Validity of order Values: `DAY`, `IOC`. |
| orders[14].price | string | No | Price at which order is placed (e.g. "250.5") |
| orders[14].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[14].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 Multi Order

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

Place a multi order directly without any conditions.

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


> **Multi-order:** Place up to 15 orders in one request. Start with Order 1 and add additional orders sequentially.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| orders[0].sequence | string | Yes | Sequence number to identify order in the batch |
| orders[0].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[0].transactionType | enum | Yes | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. Default: `BUY`. |
| orders[0].exchangeSegment | enum | Yes | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. Default: `NSE_EQ`. |
| orders[0].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. Default: `CNC`. |
| orders[0].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. Default: `LIMIT`. |
| orders[0].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. Default: `DAY`. |
| orders[0].securityId | string | No | Exchange standard identification for each scrip |
| orders[0].quantity | int | No | Number of shares or lots |
| orders[0].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[0].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[0].price | float | No | Price at which the order is requested to execute |
| orders[0].triggerPrice | float | No | Price at which the order is triggered |
| orders[0].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[1].sequence | string | No | Sequence number to identify order in the batch |
| orders[1].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[1].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[1].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[1].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[1].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[1].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[1].securityId | string | No | Exchange standard identification for each scrip |
| orders[1].quantity | int | No | Number of shares or lots |
| orders[1].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[1].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[1].price | float | No | Price at which the order is requested to execute |
| orders[1].triggerPrice | float | No | Price at which the order is triggered |
| orders[1].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[2].sequence | string | No | Sequence number to identify order in the batch |
| orders[2].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[2].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[2].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[2].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[2].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[2].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[2].securityId | string | No | Exchange standard identification for each scrip |
| orders[2].quantity | int | No | Number of shares or lots |
| orders[2].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[2].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[2].price | float | No | Price at which the order is requested to execute |
| orders[2].triggerPrice | float | No | Price at which the order is triggered |
| orders[2].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[3].sequence | string | No | Sequence number to identify order in the batch |
| orders[3].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[3].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[3].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[3].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[3].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[3].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[3].securityId | string | No | Exchange standard identification for each scrip |
| orders[3].quantity | int | No | Number of shares or lots |
| orders[3].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[3].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[3].price | float | No | Price at which the order is requested to execute |
| orders[3].triggerPrice | float | No | Price at which the order is triggered |
| orders[3].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[4].sequence | string | No | Sequence number to identify order in the batch |
| orders[4].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[4].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[4].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[4].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[4].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[4].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[4].securityId | string | No | Exchange standard identification for each scrip |
| orders[4].quantity | int | No | Number of shares or lots |
| orders[4].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[4].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[4].price | float | No | Price at which the order is requested to execute |
| orders[4].triggerPrice | float | No | Price at which the order is triggered |
| orders[4].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[5].sequence | string | No | Sequence number to identify order in the batch |
| orders[5].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[5].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[5].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[5].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[5].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[5].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[5].securityId | string | No | Exchange standard identification for each scrip |
| orders[5].quantity | int | No | Number of shares or lots |
| orders[5].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[5].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[5].price | float | No | Price at which the order is requested to execute |
| orders[5].triggerPrice | float | No | Price at which the order is triggered |
| orders[5].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[6].sequence | string | No | Sequence number to identify order in the batch |
| orders[6].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[6].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[6].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[6].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[6].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[6].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[6].securityId | string | No | Exchange standard identification for each scrip |
| orders[6].quantity | int | No | Number of shares or lots |
| orders[6].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[6].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[6].price | float | No | Price at which the order is requested to execute |
| orders[6].triggerPrice | float | No | Price at which the order is triggered |
| orders[6].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[7].sequence | string | No | Sequence number to identify order in the batch |
| orders[7].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[7].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[7].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[7].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[7].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[7].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[7].securityId | string | No | Exchange standard identification for each scrip |
| orders[7].quantity | int | No | Number of shares or lots |
| orders[7].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[7].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[7].price | float | No | Price at which the order is requested to execute |
| orders[7].triggerPrice | float | No | Price at which the order is triggered |
| orders[7].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[8].sequence | string | No | Sequence number to identify order in the batch |
| orders[8].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[8].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[8].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[8].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[8].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[8].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[8].securityId | string | No | Exchange standard identification for each scrip |
| orders[8].quantity | int | No | Number of shares or lots |
| orders[8].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[8].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[8].price | float | No | Price at which the order is requested to execute |
| orders[8].triggerPrice | float | No | Price at which the order is triggered |
| orders[8].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[9].sequence | string | No | Sequence number to identify order in the batch |
| orders[9].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[9].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[9].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[9].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[9].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[9].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[9].securityId | string | No | Exchange standard identification for each scrip |
| orders[9].quantity | int | No | Number of shares or lots |
| orders[9].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[9].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[9].price | float | No | Price at which the order is requested to execute |
| orders[9].triggerPrice | float | No | Price at which the order is triggered |
| orders[9].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[10].sequence | string | No | Sequence number to identify order in the batch |
| orders[10].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[10].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[10].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[10].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[10].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[10].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[10].securityId | string | No | Exchange standard identification for each scrip |
| orders[10].quantity | int | No | Number of shares or lots |
| orders[10].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[10].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[10].price | float | No | Price at which the order is requested to execute |
| orders[10].triggerPrice | float | No | Price at which the order is triggered |
| orders[10].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[11].sequence | string | No | Sequence number to identify order in the batch |
| orders[11].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[11].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[11].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[11].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[11].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[11].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[11].securityId | string | No | Exchange standard identification for each scrip |
| orders[11].quantity | int | No | Number of shares or lots |
| orders[11].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[11].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[11].price | float | No | Price at which the order is requested to execute |
| orders[11].triggerPrice | float | No | Price at which the order is triggered |
| orders[11].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[12].sequence | string | No | Sequence number to identify order in the batch |
| orders[12].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[12].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[12].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[12].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[12].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[12].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[12].securityId | string | No | Exchange standard identification for each scrip |
| orders[12].quantity | int | No | Number of shares or lots |
| orders[12].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[12].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[12].price | float | No | Price at which the order is requested to execute |
| orders[12].triggerPrice | float | No | Price at which the order is triggered |
| orders[12].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[13].sequence | string | No | Sequence number to identify order in the batch |
| orders[13].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[13].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[13].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[13].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[13].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[13].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[13].securityId | string | No | Exchange standard identification for each scrip |
| orders[13].quantity | int | No | Number of shares or lots |
| orders[13].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[13].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[13].price | float | No | Price at which the order is requested to execute |
| orders[13].triggerPrice | float | No | Price at which the order is triggered |
| orders[13].disclosedQuantity | int | No | Number shares visible in the market depth |
| orders[14].sequence | string | No | Sequence number to identify order in the batch |
| orders[14].correlationId | string | No | The user/partner generated id for tracking back (>= 0 characters, <= 30 characters) |
| orders[14].transactionType | enum | No | Signifies the type of transaction whether it is BUY or SELL Values: `BUY`, `SELL`. |
| orders[14].exchangeSegment | enum | No | Exchange segment for the order Values: `NSE_EQ`, `NSE_FNO`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| orders[14].productType | enum | No | Product type for the order Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orders[14].orderType | enum | No | Order type for the order Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| orders[14].validity | enum | No | Validity of the order Values: `DAY`, `IOC`. |
| orders[14].securityId | string | No | Exchange standard identification for each scrip |
| orders[14].quantity | int | No | Number of shares or lots |
| orders[14].afterMarketOrder | boolean | No | Flag to inform that the order placed is After Market Order |
| orders[14].amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |
| orders[14].price | float | No | Price at which the order is requested to execute |
| orders[14].triggerPrice | float | No | Price at which the order is triggered |
| orders[14].disclosedQuantity | int | No | Number shares visible in the market depth |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Successful operation |


### Example Request

```bash
curl --request POST \
  --url https://api.dhan.co/v2/alerts/multi/orders \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: <your-access-token>'
```

---

## 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. 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 order status ([see Annexure](/api/v2/guides/annexure#order-status)) Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| 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 order status ([see Annexure](/api/v2/guides/annexure#order-status)) Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### 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 |

---

## Sandbox

Test DhanHQ API integrations in the sandbox environment

DhanHQ Sandbox is the testing environment for DhanHQ API integrations. Use it to validate request payloads, authentication handling, response parsing, and order-management workflows before pointing your application to the live API.

Sandbox requests use the sandbox base URL:

```text
https://sandbox.dhan.co/v2
```

Generate a sandbox access token from the DhanHQ developer portal at [developer.dhanhq.co](https://developer.dhanhq.co/). Use this sandbox token in the same `access-token` request header used by production APIs.

```bash
curl --request GET \
  --url https://sandbox.dhan.co/v2/orders \
  --header 'access-token: <your-sandbox-access-token>' \
  --header 'Content-Type: application/json'
```

Sandbox and production are separate environments:

- Use `https://sandbox.dhan.co/v2` with a sandbox token for testing.
- Use `https://api.dhan.co/v2` with a production access token for live API calls.
- Both of these environments can be accessed in the documentation for testing and live API calls.
- Do not reuse production tokens for sandbox requests or sandbox tokens for production requests.
- Keep the request method, path, headers, and payload structure the same as the documented endpoint unless the endpoint documentation states otherwise.

Only endpoints marked as sandbox-enabled in this documentation are available in the sandbox environment:

| Method | Endpoint | Path |
|--------|----------|------|
| POST | [Place Order](/api/v2/orders/place-order) | `/orders` |
| PUT | [Modify Order](/api/v2/orders/modify-order) | `/orders/{orderId}` |
| DELETE | [Cancel Order](/api/v2/orders/cancel-order) | `/orders/{order-id}` |
| GET | [Get Order Book](/api/v2/orders/get-orders) | `/orders` |
| GET | [Get Order by ID](/api/v2/orders/get-order-by-id) | `/orders/{order-id}` |
| GET | [Get Order by Correlation ID](/api/v2/orders/get-order-by-correlation-id) | `/orders/external/{correlation-id}` |
| POST | [Slice Order](/api/v2/orders/slice-order) | `/orders/slicing` |
| GET | [Get Trade Book](/api/v2/orders/get-trades) | `/trades` |
| GET | [Get Trades for Order](/api/v2/orders/get-trades-by-order-id) | `/trades/{order-id}` |
| GET | [Get Holdings](/api/v2/portfolio/get-holdings) | `/holdings` |
| GET | [Get Positions](/api/v2/portfolio/get-positions) | `/positions` |
| POST | [Convert Position](/api/v2/portfolio/convert-position) | `/positions/convert` |
| POST | [Manage Kill Switch](/api/v2/traders-control/manage-kill-switch) | `/killswitch` |
| GET | [Generate T-PIN](/api/v2/edis/generate-tpin) | `/edis/tpin` |
| POST | [Generate eDIS Form](/api/v2/edis/generate-edis-form) | `/edis/bulkform` |
| GET | [EDIS Status Inquiry](/api/v2/edis/edis-inquiry) | `/edis/inquire/{isin}` |
| GET | [Get Fund Limits](/api/v2/funds/get-fund-limits) | `/fundlimit` |
| POST | [Calculate Margin](/api/v2/funds/calculate-margin) | `/margincalculator` |
| GET | [Ledger Report](/api/v2/statements/get-ledger-report) | `/ledger` |
| GET | [Trade History](/api/v2/statements/get-trade-history) | `/trades/{from-date}/{to-date}/{page-number}` |
| POST | [Get Intraday Historical Data](/api/v2/historical-data/get-intraday-historical) | `/charts/intraday` |
| POST | [Get Daily Historical Data](/api/v2/historical-data/get-daily-historical) | `/charts/historical` |

---

## 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`, `NSE_COMM`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`. |
| productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. 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 order status ([see Annexure](/api/v2/guides/annexure#order-status)) Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`, `MODIFIED`, `TRIGGERED`, `INACTIVE`. |


### 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 and Multi Order

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Place Conditional Order](/api/v2/conditional-triggers/place-conditional-trigger) | Create a new conditional trigger |
| POST | [Place Multi Order](/api/v2/conditional-triggers/place-multi-order) | Place a multi order directly without any conditions |
| PUT | [Modify Conditional Order](/api/v2/conditional-triggers/modify-conditional-trigger) | Modify an existing trigger |
| DELETE | [Delete Conditional Order](/api/v2/conditional-triggers/delete-conditional-trigger) | Delete a trigger |
| GET | [Get Conditional Order by ID](/api/v2/conditional-triggers/get-conditional-trigger-by-id) | Get a specific trigger |
| GET | [Get All Conditional Orders](/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

| Attribute | Detail |
|-----------|--------|
| `CNC` | Cash & Carry for equity deliveries |
| `INTRADAY` | Intraday for Equity, Futures & Options |
| `MARGIN` | Carry Forward in Futures & Options |
| `MTF` | Margin Trading Facility |

---

## 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 |
|-----------|--------|
| `1` | Near Expiry |
| `2` | Next Expiry |
| `3` | 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 and Multi Order

### 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": "<your-client-id>",
  "ip": "<your-static-ip>",
  "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": "<your-client-id>",
  "ip": "<your-static-ip>",
  "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 and Multi Order

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

The Conditional and Multi Order 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 Order |
| POST | `/alerts/multi/orders` | Place Multi Order |
| PUT | `/alerts/orders/{alertId}` | Modify Conditional Order |
| DELETE | `/alerts/orders/{alertId}` | Delete Conditional Order |
| GET | `/alerts/orders/{alertId}` | Get Conditional Order by ID |
| GET | `/alerts/orders` | Get All Conditional Orders |

> **note:** - Conditional Orders 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 Order

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 Order

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 Order](#place-conditional-order), with the addition of `alertId` as a path parameter.

**Response**

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

---

## Delete Conditional Order

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 Order 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 Orders

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-order-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."
}
```

> **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=<your-access-token>&clientId=<your-client-id>&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=<your-access-token>&clientId=<your-client-id>&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:** 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 |
|-------|------|------|-------------|
| 0-1 | int16 | 2 | Message Length of the entire payload packet |
| 2 | [ ] byte | 1 | Feed Response Code can be referred in [Annexure](/api/v2/guides/annexure#feed-response-code) |
| 3 | [ ] byte | 1 | Exchange Segment can be referred in [Annexure](/api/v2/guides/annexure#exchange-segment) |
| 4-7 | int32 | 4 | Security ID - can be found [here](/api/v2/guides/instruments) |
| 8-11 | 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-11 | [ ] array | 12 | [Response Header](#response-header)
`41` for Bid Data (Buy)
`51` for Ask Data (Sell) (see Annexure) |
| 12-331 | 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 |
|-------|------|------|-------------|
| 0-7 | float64 | 8 | Price |
| 8-11 | uint32 | 4 | Quantity |
| 12-15 | 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 |
|-------|------|------|-------------|
| 0-1 | int16 | 2 | Message Length of the entire payload packet |
| 2 | [ ] byte | 1 | Feed Response Code can be referred in [Annexure](/api/v2/guides/annexure#feed-response-code) |
| 3 | [ ] byte | 1 | Exchange Segment can be referred in [Annexure](/api/v2/guides/annexure#exchange-segment) |
| 4-7 | int32 | 4 | Security ID - can be found [here](/api/v2/guides/instruments) |
| 8-11 | 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-11 | [ ] array | 12 | [Response Header](#response-header-1)
`41` for Bid Data (Buy)
`51` for Ask Data (Sell) (see Annexure) |
| 12-3211 | 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 |
|-------|------|------|-------------|
| 0-7 | float64 | 8 | Price |
| 8-11 | uint32 | 4 | Quantity |
| 12-15 | uint32 | 4 | No. of Orders |

> **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-11 | [ ] array | 12 | [Response Header](#response-header-1) with code `50` (see Annexure) |
| 12-13 | 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 is a state-of-the-art platform that enables you to build trading and investment services, applications, and strategies.

It provides a set of REST-like APIs that integrate directly with our trading platform. With DhanHQ APIs, you can execute and modify orders in real time, manage portfolios, access live market data, and more through a fast and reliable API collection.

The platform uses resource-based URLs and supports JSON as well as form-encoded requests. Responses are returned in JSON format using standard HTTP response codes, verbs, and authentication methods.

## 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

## Indian Stocks

You can fetch instrument lists for all Indian 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 |

---

## Global Stocks

You can fetch the instrument list for global stocks tradable via Dhan using this URL:

```
https://api-global-stocks.dhan.co/api-data/us-stock-scrip-master.csv
```

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

### Column Description

| Column | Description |
|---|---|
| `EXCHANGE` | Internal exchange code, e.g. `INX` for international/US stocks |
| `SEGMENT` | Segment type, `E` = Equity |
| `SCRIP_CODE` | Unique security/instrument ID used by broker/API |
| `ISIN_CODE` | ISIN of the US security |
| `SYMBOL` | Stock/ETF ticker symbol |
| `SYMBOL_NAME` | Official company/fund name |
| `EXCH_SYMBOL` | Symbol on actual US exchange |
| `CUSTOM_SYMBOL` | Display name shown on platform |
| `TRADING_SYMBOL` | Symbol used for trading/orders |
| `FRACTION` | Whether fractional investing is allowed |
| `CUSTOM_EXCH` | Actual exchange: NYSE, NASDAQ, CBOE, NYSE Arca |
| `INSTRUMENT_NAME` | Instrument type, usually `EQUITY` |
| `TICK_SIZE` | Minimum price movement |
| `LOT_SIZE` | Minimum quantity unit |
| `UPPER_LIMIT` | Maximum allowed order price |
| `LOWER_LIMIT` | Minimum allowed order price |
| `UPDATE_DATE` | Last updated timestamp |

---

## 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-oss/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=<your-access-token>&clientId=<your-client-id>&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:** 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 |
|-------|------|------|-------------|
| 0 | [ ] byte | 1 | Feed Response Code can be referred in [Annexure](/api/v2/guides/annexure#feed-response-code) |
| 1-2 | int16 | 2 | Message Length of the entire payload packet |
| 3 | [ ] byte | 1 | Exchange Segment can be referred in [Annexure](/api/v2/guides/annexure#exchange-segment) |
| 4-7 | 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-7 | [ ] array | 8 | [Response Header](#response-header) with code `2` (see Annexure) |
| 8-11 | float32 | 4 | Last Traded Price of the subscribed instrument |
| 12-15 | 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-7 | [ ] array | 8 | [Response Header](#response-header) with code `6` (see Annexure) |
| 8-11 | float32 | 4 | Previous day closing price |
| 12-15 | 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-7 | [ ] array | 8 | [Response Header](#response-header) with code `4` (see Annexure) |
| 8-11 | float32 | 4 | Latest Traded Price of the subscribed instrument |
| 12-13 | int16 | 2 | Last Traded Quantity |
| 14-17 | int32 | 4 | Last Trade Time (LTT) - EPOCH |
| 18-21 | float32 | 4 | Average Trade Price (ATP) |
| 22-25 | int32 | 4 | Volume |
| 26-29 | int32 | 4 | Total Sell Quantity |
| 30-33 | int32 | 4 | Total Buy Quantity |
| 34-37 | float32 | 4 | Day Open Value |
| 38-41 | float32 | 4 | Day Close Value - only sent post market close |
| 42-45 | float32 | 4 | Day High Value |
| 46-49 | 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-7 | [ ] array | 8 | [Response Header](#response-header) with code `5` (see Annexure) |
| 8-11 | 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-7 | [ ] array | 8 | [Response Header](#response-header) with code `8` (see Annexure) |
| 8-11 | float32 | 4 | Latest Traded Price of the subscribed instrument |
| 12-13 | int16 | 2 | Last Traded Quantity |
| 14-17 | int32 | 4 | Last Trade Time (LTT) - EPOCH |
| 18-21 | float32 | 4 | Average Trade Price (ATP) |
| 22-25 | int32 | 4 | Volume |
| 26-29 | int32 | 4 | Total Sell Quantity |
| 30-33 | int32 | 4 | Total Buy Quantity |
| 34-37 | int32 | 4 | Open Interest in the contract (for Derivatives) |
| 38-41 | int32 | 4 | Highest Open Interest for the da (only for NSE_FNO) |
| 42-45 | int32 | 4 | Lowest Open Interest for the day (only for NSE_FNO) |
| 46-49 | float32 | 4 | Day Open Value |
| 50-53 | float32 | 4 | Day Close Value - only sent post market close |
| 54-57 | float32 | 4 | Day High Value |
| 58-61 | float32 | 4 | Day Low Value |
| 62-161 | 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 |
|-------|------|------|-------------|
| 0-3 | int32 | 4 | Bid Quantity |
| 4-7 | int32 | 4 | Ask Quantity |
| 8-9 | int16 | 2 | No. of Bid Orders |
| 10-11 | int16 | 2 | No. of Ask Orders |
| 12-15 | float32 | 4 | Bid Price |
| 16-19 | 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-7 | [ ] array | 8 | [Response Header](#response-header) with code `50` (see Annexure) |
| 8-9 | 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": "<your-client-id>",
        "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": "<your-client-id>",
        "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`. |
| 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 and Multi Order, P&L based exit under Trader's Control, and Exit All API.

### New Features

- **Conditional and Multi Order** — 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

### 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, 30, 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 Trading Facility |

### 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": "<your-client-id>",
    "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": "<your-client-id>",
        "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`. |
| 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
export DHAN_ACCESS_TOKEN="your-access-token-here"
```

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
export DHAN_CLIENT_ID="your-client-id"
```

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
│   ├── 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)

---

## Compute Tiers

Dhan Cloud compute tier specs and per-strategy isolation model.

Each strategy you deploy runs on its own compute instance. You select the tier for each strategy in the **Settings** section of the strategy editor.

## Current Tier

| Spec | Value |
|---|---|
| CPU | 1 vCPU |
| Memory | 3 GB RAM |
| Strategies running in parallel | No limit. Each strategy gets its own instance. |
| Log retention | Unlimited |

> **note:** Additional tiers are planned. Check the Settings section in the dashboard for currently available options and pricing.

## Per-Strategy Isolation

Every strategy runs on a dedicated instance. One strategy cannot affect the performance or resources of another.

---

## Credits

Dhan Cloud credit-based billing, free credits on signup, topping up from Dhan ledger, and low-balance behavior.

Dhan Cloud uses a credit-based billing model. Running strategies consume credits over time. When credits run out, strategies stop.

## Free Credits on Signup

Every new Dhan Cloud account starts with **100 free compute credits**, applied automatically when you sign up. No payment is required to get started.

## Adding Credits

Credits are purchased using your Dhan ledger balance.

1. Go to **Settings** in the Dhan Cloud dashboard
2. Select a top-up amount
3. The amount is deducted from your Dhan ledger and added to your Cloud credit balance

> **note:** Topping up requires a connected Dhan account. See [Getting Started](/cloud/getting-started) if you have not connected one yet.

## Low Balance Warning

When your balance drops below **50 credits**, a warning banner appears in the dashboard. Your strategies continue running, but you should add credits soon.

> **warning:** When your balance reaches 0, all running strategies stop. To avoid interruption, top up before running out.

## Credit Consumption

How quickly credits are consumed depends on the compute tier and how long your strategies run. You can check your current balance and usage history in **Settings, Credits**.

---

## Dependencies

How to declare and manage Python package dependencies for Dhan Cloud strategies.

Dhan Cloud installs Python packages fresh on each deployment based on what you declare in the **Dependencies** tab. There is no pre-installed package list. Every package your strategy needs, including `dhanhq`, must be declared.

## Declaring Dependencies

In the **Dependencies** tab, list one package per line:

```
dhanhq==2.0.1
scipy==1.11.0
ta-lib==0.4.28
```
> **tip:** It is necessary to specify the package version every time a dependency is added to the dependencies section.

## How Packages Are Evaluated

Dhan Cloud installs packages from public PyPI. Before installing, each package is checked against the **Python Packaging Advisory Database** and the **OSV (Open Source Vulnerabilities)** database. Packages with known security advisories are rejected. All other packages install normally.

> **warning:** If a package fails to install, your strategy will not start and you will see an error in the Logs. Double-check the package name on PyPI and consider pinning an older version if the latest has a known issue.

---

## Execution Environment

Python version, runtime restrictions, persistent storage, and execution model for Dhan Cloud strategies.

Dhan Cloud strategies run in an isolated Python container. Each deployment gets a fresh environment. Understanding this helps you avoid common issues.

## Python Version

Python **3.11**. The runtime version is managed by Dhan Cloud and cannot be changed.

## Restricted Operations

The following operations are blocked. If your code uses any of them, the code scanner will prevent deployment.

| Operation | Why it is blocked | What to use instead |
|---|---|---|
| `os.getenv()` | Environment variables are not available in the container | Use `{{VAR_NAME}}` variables |
| `os.path` and other filesystem checks | Container filesystem is not accessible | Use in-memory state |
| `subprocess`, `os.system()`, `os.popen()` | Shell access is not permitted | Not supported; remove these calls |
| Writing files (`open(..., 'w')`) | No writable filesystem | Use `print()` for logging |
| Excel packages (`openpyxl`, `xlwt`, `xlrd`) | Flagged by the security scanner | Use pandas DataFrames in memory |

> **warning:** `os.getenv()` and `os.path` are hard blocked. Code using these will fail the scanner and cannot be deployed. Use the [Variables](/cloud/core-concepts/variables) system instead.

## Persistent Storage

There is no persistent file storage between runs. If your strategy exits and restarts, any local state is lost.

If you need to persist state across runs, options include:

- Writing to an external database via HTTP API (e.g. Firebase, Supabase, or any REST-accessible store)
- Logging events to an external service

## Execution Model

Strategies run as a continuous Python process. Use a `while True` loop with `time.sleep()` to control how frequently your logic executes.

```python
import time

while True:
    run_strategy()
    time.sleep(60)  # runs once per minute
```

> **warning:** Always include `time.sleep()` inside your loop. A loop without a sleep will consume CPU at maximum rate and may be terminated.

---

## Variables

Inject credentials and config into strategies using Dhan Cloud's Variables system, global and strategy-scoped.

let you inject credentials and configuration into strategies without writing sensitive values directly in code. When your strategy runs, Dhan Cloud substitutes the placeholders with the actual values. The values are never visible in logs or stored in your strategy code.

There are two scopes:

## Global Variables

Global variables are defined once and are available to every strategy in your account. Use them for credentials or config that multiple strategies share.

| Use for | Examples |
|---|---|
| Shared API credentials | `CLIENT_ID`, `ACCESS_TOKEN` |
| Common configuration | `RISK_PER_TRADE`, `MAX_POSITION_SIZE` |

Set in: Dashboard, **Settings, Global Variables**

## Strategy Variables

Strategy variables are scoped to a single strategy. If a strategy variable and a global variable share the same name, the strategy variable takes precedence.

Set in: Strategy editor, **Variables tab**

## Using Variables in Code

Reference a variable in your code using double-brace syntax:

```python
client_id    = "{{CLIENT_ID}}"
access_token = "{{ACCESS_TOKEN}}"
```

At runtime, `{{CLIENT_ID}}` is replaced with the actual value you configured.

> **warning:** Do not use `os.getenv()` to read credentials. Environment variables are not available in Dhan Cloud containers. Use the `{{VAR_NAME}}` syntax instead.

> **tip:** Variable names are case-sensitive. `{{CLIENT_ID}}` and `{{client_id}}` are treated as different variables.

---

## Versions

How strategy versioning works in Dhan Cloud, including saving, restoring, and the relationship between editor and deployed versions.

Every time you save a strategy, Dhan Cloud asks how you want to save it:

- **Save as new version** creates a new entry in the version history. The previous version is preserved and can be restored later.
- **Overwrite current version** replaces the current version. The previous state is not retained.

## Version History

Saved versions appear under the **Versions** tab with a timestamp. You can view or restore any version from this list.

> **tip:** Use "Save as new version" before making significant changes. It gives you a checkpoint to return to if something breaks.

## A Few Things to Know

- Version history is per-strategy. Versions are not shared between strategies.
- Restoring a version replaces the current editor content, including code and dependencies.
- The version in the editor and the currently deployed version can be different. Clicking Deploy always uses whatever is currently in the editor.

---

## Getting Started

Connect your Dhan account and deploy your first Python strategy on Dhan Cloud.

## Connect Your Dhan Account

Before you can deploy strategies, you need to connect your Dhan trading account via the Developer Portal. This is a one-time step required for regulatory compliance and links your Dhan ledger balance for billing.

> **note:** Connecting your account does not authorize Dhan Cloud to place orders on your behalf. Orders can only be placed by your strategy code, using the API credentials you configure in Variables. Without those credentials in your code, no orders will be placed.

### Step 1 — Sign in to the Developer Portal

Go to [developer.dhanhq.co](https://developer.dhanhq.co) and sign in or create an account.

### Step 2 — Connect your Dhan account

Follow the steps in the portal to connect your Dhan trading account. Once connected, your Dhan ledger balance can be used to purchase cloud credits.

### Credentials you will need

To place orders and fetch market data, your strategy needs two credentials from Dhan:

| Credential | Where to find it |
|---|---|
| Client ID | Dhan app, under Profile |
| Access Token | [developer.dhanhq.co](https://developer.dhanhq.co), under Access Token |

You will add these to your strategy using Variables, not by writing them directly in code. See [Variables](/cloud/core-concepts/variables) for how this works.

---

## Deploy Your First Strategy

This walkthrough creates and deploys a minimal strategy that fetches a live stock quote and prints it to the logs.

### Step 1 — Create a new strategy

In the Dhan Cloud dashboard, click **New Strategy**. Give it a name.

### Step 2 — Write the strategy

Paste the following into the editor. This strategy fetches the live price of Infosys (security ID `1333` on NSE) and prints it once a minute.

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

client_id    = "{{CLIENT_ID}}"
access_token = "{{ACCESS_TOKEN}}"

dhan = dhanhq(DhanContext(client_id, access_token))

while True:
    quote = dhan.ticker_data(securities={"NSE_EQ": [1333]})
    print(f"Infosys LTP: {quote}")
    time.sleep(60)
```

### Step 3 — Set your credentials in Variables

Go to the **Variables** tab and add:

- `CLIENT_ID` with your Dhan client ID
- `ACCESS_TOKEN` with your access token from [developer.dhanhq.co](https://developer.dhanhq.co)

The `{{CLIENT_ID}}` and `{{ACCESS_TOKEN}}` placeholders in your code are replaced with these values at runtime.

### Step 4 — Add the SDK to Dependencies

Go to the **Dependencies** tab and add:

```
dhanhq
```

Dhan Cloud installs packages fresh on each deployment. Even `dhanhq` must be declared here. See [Dependencies](/cloud/core-concepts/dependencies) for more.

### Step 5 — Select a compute tier

In the Settings section, select a compute tier. See [Compute Tiers](/cloud/core-concepts/compute-tiers) for available specs.

### Step 6 — Save and deploy

Click **Save**. You will be asked whether to save as a new version or overwrite the current one. For a first strategy, choose **Save as new version**.

Click **Deploy**. Dhan Cloud runs a code scan first. If the scan passes, the strategy is queued for execution. You can watch live output in the **Logs** tab.

> **tip:** If your strategy does not appear to be running, check the Logs tab first. Most issues (missing packages, wrong credentials) show up there immediately.

See [Versions](/cloud/core-concepts/versions) for how to manage version history and roll back changes.

---

## Testing with Sandbox

Dhan provides a sandbox environment where you can test order placement without using real funds. To use it, get sandbox credentials from [developer.dhanhq.co](https://developer.dhanhq.co) and set your strategy to use the sandbox API endpoint:

```python
# Use separate Variables for sandbox credentials
client_id    = "{{SANDBOX_CLIENT_ID}}"
access_token = "{{SANDBOX_ACCESS_TOKEN}}"

# Sandbox base URL: https://sandbox.dhan.co/v2/
```

The sandbox behaves like the live API but does not execute real orders.

---

## Dhan Cloud

Deploy and run algorithmic trading strategies on Dhan's managed cloud infrastructure.

**Managed infrastructure for algorithmic trading strategies.**

Dhan Cloud lets you deploy, run, schedule, and scale Python trading strategies on low-latency infrastructure co-located with Indian exchanges — without managing servers or worrying about uptime during market hours.

---

## Why Dhan Cloud

- **Zero infrastructure** — No servers to provision or maintain
- **Co-located execution** — Low-latency connectivity to NSE, BSE, MCX
- **Python native** — Write strategies using the DhanHQ SDK you already know
- **Secure by design** — Code scanning, sandboxed execution, credential isolation
- **Pay per use** — Credit-based billing tied to compute tiers

---

## How it works

1. Write your strategy in Python using the DhanHQ SDK
2. Set credentials and config via secure Variables
3. Declare dependencies (packages installed fresh each deploy)
4. Choose a compute tier and deploy
5. Monitor via live logs

---

## Next steps

- [Getting Started](/cloud/getting-started) — Connect your account and deploy your first strategy
- [Execution Environment](/cloud/core-concepts/execution-environment) — What runs inside Dhan Cloud
- [Compute Tiers](/cloud/core-concepts/compute-tiers) — Available specs and pricing
- [Variables](/cloud/core-concepts/variables) — Securely pass credentials to your code
- [Dependencies](/cloud/core-concepts/dependencies) — Managing Python packages
- [Writing Strategies](/cloud/writing-strategies/) — Patterns and SDK usage
- [Security](/cloud/security/code-scanner) — Code scanning and allowed operations

---

## Common Errors

Common errors in Dhan Cloud strategies and how to fix them, covering deployment, auth, orders, rate limits, SDK, and Python issues.

## Deployment Errors

**`ModuleNotFoundError: No module named 'dhanhq'`** (or `requests`, `pandas`, `numpy`)

The package is not listed in Dependencies. Add it to the **Dependencies** tab:
```
dhanhq
pandas
numpy
requests
```

---

**`[pip] ERROR: Invalid requirement: 'pip install dhanhq'`**

The Dependencies tab takes package names only, not install commands. Remove `pip install` and list just the name:
```
dhanhq
```

---

**`[pip] ERROR: No matching distribution found for time`**

`time` is part of Python's standard library and cannot be installed via pip. Remove it from Dependencies. Use `import time` in your code directly.

---

**`SyntaxError`** / **`IndentationError`**

Usually caused by indentation corruption from copy-pasting in the browser editor. To fix:
1. Copy your code into a local editor (VS Code or PyCharm)
2. Fix indentation using 4 spaces, not tabs
3. Paste the corrected code back

---

**`Code validation failed` (scanner block)**

The security scanner flagged something in your code. Any flag blocks deployment. See [Code Scanner](/cloud/security/code-scanner) for how to identify and fix specific flags.

---

## Authentication Errors

**`DH-901` — access token invalid or expired**
```json
{"errorType": "Invalid_Authentication", "errorCode": "DH-901", "errorMessage": "Client ID or user generated access token is invalid or expired."}
```
Your access token has expired or does not match the Client ID. Fix:
1. Regenerate your access token at [developer.dhanhq.co](https://developer.dhanhq.co)
2. Update the `ACCESS_TOKEN` variable in your strategy
3. Confirm that `CLIENT_ID` matches your Dhan account

---

**`Login failed. Please retry with valid credentials.`**

Credentials are wrong or the login flow failed. Check `CLIENT_ID`, `ACCESS_TOKEN`, and any TOTP configuration in Variables.

---

**`Token can be generated once every 2 minutes.`**

Your strategy is trying to generate an access token too frequently. Generate it once at startup and reuse it throughout the session. Do not call token generation inside a loop.

---

**`HTTP Error 401: Unauthorized`**

The access token expired during a run or was not injected correctly. Regenerate the token and update the `ACCESS_TOKEN` variable. If you generate the token programmatically, make sure the generation call succeeds before any API calls are made.

---

## Order and Trading Errors

**`DH-906` — market is closed**
```json
{"errorType": "Order_Error", "errorCode": "DH-906", "errorMessage": "Market is Closed! Want to place an offline order?"}
```
An order was placed outside of market hours. NSE/BSE equity hours are 9:15 AM to 3:30 PM IST on weekdays. Add a market hours check:

```python
from datetime import datetime
import pytz

def is_market_open():
    now = datetime.now(pytz.timezone('Asia/Kolkata'))
    return now.weekday() < 5 and 9 * 60 + 15 <= now.hour * 60 + now.minute <= 15 * 30

if is_market_open():
    dhan.place_order(...)
```

---

**`DH-905` — missing or invalid parameters**
```json
{"errorType": "Input_Exception", "errorCode": "DH-905"}
```
A required field is missing or has an invalid value. Check that `security_id`, `exchange_segment`, `transaction_type`, `quantity`, `order_type`, and `validity` are all correct. Refer to [Order API docs](https://docs.dhanhq.co).

---

**`Order failed: Unknown error`**

An unspecified error from the order management system, usually transient. Implement retry logic with a delay. If it persists, check the full response body in logs for an `omsErrorDescription` field.

---

**`omsErrorDescription: RMS:...:You have insufficient funds`**

Insufficient margin for the order size. Reduce position size or add funds to your trading account. You can check available margin with:
```python
funds = dhan.get_fund_limits()
```

---

## Rate Limiting

**`HTTP Error 429: Too Many Requests`**
```
{"data": {"805": "Too many requests. Further requests may result in the user being blocked."}}
```
Your strategy is calling Dhan APIs too frequently. Dhan enforces per-second and per-minute rate limits on data and order endpoints. Fix:

1. Add `time.sleep()` between API calls
2. Use exponential backoff on 429 responses
3. Cache historical data instead of fetching it on every loop iteration

```python
import time

def fetch_with_retry(fn, *args, retries=3, delay=5):
    for i in range(retries):
        result = fn(*args)
        if result:
            return result
        time.sleep(delay * (2 ** i))
    return None
```

---

**`YFRateLimitError` (yfinance)**

yfinance is being called too frequently. Cache the results and reduce call frequency. For Indian market data, consider using Dhan's own data APIs instead.

---

## SDK Errors

**`'dhanhq' object has no attribute 'get_ticker_data'`** or **`'historical_data'`**

These method names changed in SDK v2. Use the current names:
- `get_ticker_data` is now `ticker_data`
- `historical_data` is now `historical_daily_data` or `intraday_minute_data`

See the [dhanhq changelog](https://github.com/dhan-oss/DhanHQ-py) for a full list of renamed methods.

---

**`'list' object has no attribute 'items'`** from `ticker_data`

`ticker_data` returned a list rather than a dict. Handle both cases:
```python
data = dhan.ticker_data(...)
if isinstance(data, list):
    for item in data:
        process(item)
elif isinstance(data, dict):
    process(data)
```

---

**`json.decoder.JSONDecodeError: Expecting value`**

The API returned an empty response body, usually because of an auth failure or rate limit. Check the HTTP status code before parsing:
```python
response = requests.get(url, headers=headers)
if response.status_code != 200 or not response.text:
    print(f"API error {response.status_code}: {response.text}")
    return None
data = response.json()
```

---

**`404 Client Error`**

The endpoint URL is wrong. Check the [API docs](https://docs.dhanhq.co) for the correct path.

---

**`Error parsing option chain: 'last_price'`**

The option chain response does not contain the key you expected. Use `.get()` with a fallback:
```python
ltp = option_data.get('last_price') or option_data.get('ltp')
if ltp is None:
    print("Unexpected response structure:", option_data.keys())
```

---

## Python and pandas Errors

**`TypeError: NDFrame.fillna() got an unexpected keyword argument 'method'`**

The `method` parameter was removed from `fillna()` in pandas 2.x. Use `ffill()` directly:
```python
df['col'].ffill()
```

---

**`pandas.errors.NullFrequencyError: Cannot shift with no freq`**

The DatetimeIndex has no frequency set. Set it explicitly or use `pct_change()` instead of shift-based calculations:
```python
df.index.freq = pd.tseries.frequencies.to_offset('1min')
# or
df['returns'] = df['close'].pct_change()
```

---

**`ChainedAssignmentError`**

pandas 2.x raises an error (not just a warning) for chained assignment. Use `.loc` instead:
```python
# Wrong
df[df['signal'] == 1]['qty'] = 10

# Correct
df.loc[df['signal'] == 1, 'qty'] = 10
```

---

**`ValueError: The truth value of a Series is ambiguous`**

You are using a pandas Series in a boolean context. Use `.any()`, `.all()`, or `.empty`:
```python
if not df['signal'].empty and df['signal'].any():
    ...
```

---

**`KeyError: 0`** or **`IndexError: single positional indexer is out-of-bounds`**

The DataFrame is empty or you are using integer indexing on a non-integer index. Always check before accessing:
```python
if not df.empty:
    row = df.iloc[0]
```

---

**`NameError: name 'X' is not defined`**

A variable is used before it is assigned. This often happens when a variable is defined inside a conditional block that was not reached. Initialize all variables at the top of your function:
```python
start_hour = 9
```

---

## Runtime Issues

**Strategy runs once and stops**

Your strategy needs a `while True` loop with `time.sleep()` to keep running:
```python
import time
while True:
    run_strategy()
    time.sleep(60)
```

---

**Orders not placing, no error in logs**

Variable syntax is wrong. Double braces are required:
```python
client_id = "{{CLIENT_ID}}"   # correct
client_id = "{CLIENT_ID}"     # wrong, treated as a literal string
```

---

**`AuthError` or `Invalid Token`**

Access token has expired. Regenerate it at [developer.dhanhq.co](https://developer.dhanhq.co) and update the `ACCESS_TOKEN` variable.

---

## Editor Issues

**Indentation errors after editing**

The browser editor can corrupt indentation in files over roughly 200 lines. Edit large files locally and paste the full content at once.

**Error traceback points to the wrong line**

Python tracebacks can be offset from the actual error. Look at the 10 lines above the reported line number for unclosed brackets, missing colons, or broken indentation.

---

## Dhan API Error Code Reference

| Error Code | Error Type | Cause |
|---|---|---|
| `DH-901` | `Invalid_Authentication` | Access token expired or Client ID mismatch |
| `DH-905` | `Input_Exception` | Missing or invalid order parameters, or rate limit hit |
| `DH-906` | `Order_Error` | Order placed outside market hours |
| `DH-907` | `Order_Error` | Insufficient funds in account |

Full reference: [docs.dhanhq.co/api/v2/guides/errors](https://docs.dhanhq.co/api/v2/guides/errors)

---

## No Static IP Required

Strategies on Dhan Cloud run on Dhan's own infrastructure and connect to Dhan APIs internally. You do not need to whitelist an IP address or set up firewall rules. Access token credentials are the only thing needed to authenticate.

---

## Allowed Operations

What Python operations are allowed and blocked in Dhan Cloud's isolated container environment.

# Allowed and Restricted Operations

Dhan Cloud strategies run in an isolated container. The following tables describe what is and is not permitted.

## Allowed

| Operation | Notes |
|---|---|
| `requests.get()` / `requests.post()` | Outbound HTTP is permitted to any host |
| `print()` | Output appears in real time in the Logs tab |
| `time.sleep()` | Required inside loops to control execution cadence |
| `pandas`, `numpy`, and most PyPI packages | Declare in Dependencies |
| `dhanhq` | Official Dhan SDK. Declare in Dependencies. |

## Blocked

| Operation | Notes |
|---|---|
| `subprocess`, `os.system()`, `os.popen()` | Shell execution is not supported |
| `os.getenv()` | Environment variables are not available. Use the Variables system instead. |
| `os.path` and filesystem operations | The container filesystem is not accessible |
| Writing files (`open(..., 'w')`) | No writable filesystem. Use `print()` for logging. |
| Excel packages (`openpyxl`, `xlwt`, `xlrd`) | Flagged by the security scanner. Use pandas DataFrames. |
| Binding to network ports | Container networking is isolated |

## Outbound HTTP

There is no allowlist for outbound HTTP. Your strategy can make requests to any public host, including:

- `api.dhan.co` for Dhan trading and market data APIs
- `nseindia.com` or `bseindia.com` for exchange data
- Any other public API your strategy needs

---

## Code Scanner

How Dhan Cloud's AI code scanner works, what it checks, risk levels, common flags and how to fix them.

Every deployment goes through an automated security scan before your strategy starts. This is mandatory. If the scan flags anything, deployment is blocked until you resolve the issues.

## What the Scanner Checks

The scanner uses AI to analyze your code for patterns that could pose a security or stability risk in a shared cloud environment:

| Category | What it looks for |
|---|---|
| Credential exposure | Hardcoded tokens, passwords, or client codes |
| System access | Shell execution, filesystem reads and writes |
| Infinite resource consumption | Loops without throttling, uncontrolled memory use |
| Dependency risk | Packages that wrap or obscure dangerous operations |

## Risk Levels

| Level | What it means | Effect |
|---|---|---|
| `LOW` | Minor concern | Deployment blocked |
| `MEDIUM` | Security concern | Deployment blocked |
| `HIGH` | Security violation | Deployment blocked |

Every flag blocks deployment regardless of severity. There is no way to acknowledge a flag and proceed anyway. All issues must be resolved before you can deploy.

The scanner is AI-powered, which means identical code can occasionally produce slightly different results between scans. If you receive an unexpected flag on code that should be clean, re-save and try again once before investigating further.

## Common Flags and How to Fix Them

**Flag: Hardcoded credentials**
```
The code contains sensitive information placeholders like {CLIENT_CODE}, {TOKEN}
```
- **Risk level:** MEDIUM
- **Fix:** Use double-brace variable syntax. A single brace like `{CLIENT_CODE}` is treated as a literal string, not a variable reference.
```python
# Wrong
client_code = "{CLIENT_CODE}"

# Correct
client_code = "{{CLIENT_CODE}}"
```

---

**Flag: subprocess or shell execution**
```
The code uses subprocess execution
```
- **Risk level:** HIGH
- **Fix:** Remove all `subprocess`, `os.system()`, and `os.popen()` calls. Shell execution is not supported in Dhan Cloud.

---

**Flag: os.getenv() usage**
```
The code uses os.getenv() to read environment variables
```
- **Risk level:** MEDIUM / HIGH
- **Fix:** Replace with variable syntax. Environment variables are not available inside the container.
```python
# Remove this
import os
token = os.getenv("ACCESS_TOKEN")

# Use this instead
token = "{{ACCESS_TOKEN}}"
```

---

**Flag: Infinite loop without throttling**
```
The code runs in an infinite loop which could lead to resource exhaustion
```
- **Risk level:** HIGH
- **Fix:** Add `time.sleep()` inside the loop.
```python
while True:
    run_strategy()
    time.sleep(60)
```

---

**Flag: External HTTP requests**
```
The code makes HTTP requests to external APIs
```
- **Risk level:** MEDIUM (informational)
- **Fix:** No action needed if you are fetching public market data. This flag is raised for awareness. Outbound HTTP to any host is permitted.

---

**Flag: Tradehull library usage**
```
The code uses the Tradehull library which appears to be a wrapper around trading APIs
```
- **Risk level:** LOW (informational)
- **Fix:** No action needed. Tradehull is explicitly allowed on Dhan Cloud.

## If Your Strategy Is Blocked

1. Read the issue list shown in the scan result
2. Fix each flagged item using the guidance above
3. Re-save and re-deploy. The scanner runs on every deployment.

> **tip:** If you believe a flag is a false positive, use the **Feedback** option in the left navigation bar to report it. The Dhan team reviews feedback and updates the scanner accordingly.

---

## DhanHQ SDK

Using the official DhanHQ Python SDK in Dhan Cloud, including market data, order placement, and fund limits.

The `dhanhq` package is the official Dhan Python SDK. Add it to your Dependencies tab and use it to place orders, fetch market data, and check account balances.

SDK reference: [github.com/dhan-oss/DhanHQ-py](https://github.com/dhan-oss/DhanHQ-py)

## Initialization

```python
from dhanhq import DhanContext, dhanhq

client_id    = "{{CLIENT_ID}}"
access_token = "{{ACCESS_TOKEN}}"

dhan = dhanhq(DhanContext(client_id, access_token))
```

## Market Data

Fetch live prices for one or more instruments using their security IDs. Security IDs are Dhan's internal instrument identifiers (e.g. `1333` is Infosys on NSE).

```python
# Last traded price
quote = dhan.ticker_data(securities={"NSE_EQ": [1333]})

# OHLC (open, high, low, close)
ohlc = dhan.ohlc_data(securities={"NSE_EQ": [1333]})

# Full market depth quote
full = dhan.quote_data(securities={"NSE_EQ": [1333]})
```

## Historical Data

```python
from datetime import date, timedelta

to_date   = date.today().isoformat()
from_date = (date.today() - timedelta(days=30)).isoformat()

# Minute-level intraday candles
intraday = dhan.intraday_minute_data(
    security_id="1333",
    exchange_segment="NSE_EQ",
    instrument_type="EQUITY",
    from_date=from_date,
    to_date=to_date
)

# Daily end-of-day candles
daily = dhan.historical_daily_data(
    security_id="1333",
    exchange_segment="NSE_EQ",
    instrument_type="EQUITY",
    from_date=from_date,
    to_date=to_date
)
```

## Placing an Order

```python
dhan.place_order(
    security_id="1333",
    exchange_segment=dhan.NSE,
    transaction_type=dhan.BUY,
    quantity=1,
    order_type=dhan.MARKET,
    product_type=dhan.INTRA,
    price=0
)
```

Use these constants for `exchange_segment`, `transaction_type`, `order_type`, and `product_type`:

| Parameter | Available values |
|---|---|
| Exchange segment | `dhan.NSE`, `dhan.BSE`, `dhan.NSE_FNO`, `dhan.MCX` |
| Transaction type | `dhan.BUY`, `dhan.SELL` |
| Order type | `dhan.MARKET`, `dhan.LIMIT`, `dhan.SL`, `dhan.SLM` |
| Product type | `dhan.INTRA` (intraday), `dhan.CNC` (delivery), `dhan.MARGIN` |

## Checking Fund Limits

Returns available margin, used margin, and other balance details for your account.

```python
funds = dhan.get_fund_limits()
print(funds)
```

---

## Writing Strategies

How to write, structure, and deploy Python trading strategies on Dhan Cloud.

A strategy on Dhan Cloud is a Python script. It runs in a managed container with access to the Dhan trading APIs via the official DhanHQ SDK (`dhanhq`).

## Using the DhanHQ SDK

The DhanHQ SDK is the primary way to interact with Dhan from your strategy. It provides methods for placing orders, fetching market data, and checking account balances.

Add `dhanhq` to your Dependencies tab, then initialize it with your credentials:

```python
from dhanhq import DhanContext, dhanhq

client_id    = "{{CLIENT_ID}}"
access_token = "{{ACCESS_TOKEN}}"

dhan = dhanhq(DhanContext(client_id, access_token))
```

Full SDK reference: [github.com/dhan-oss/DhanHQ-py](https://github.com/dhan-oss/DhanHQ-py)

## Creating a Strategy

Click **New Strategy** in the dashboard to start. You can choose from three creation methods:

- **Blank** — start from an empty editor
- **Template** — pick from a set of pre-built starting points
- **Pine Script to Python** — paste a TradingView Pine Script and convert it to Python using AI

## Single-File and Multi-File Strategies

The editor supports both single-file and multi-file strategies. If your strategy spans multiple Python files, you can add them as separate files in the editor. You can also include data files such as CSV files with symbol lists or reference data.

## Minimal Strategy Structure

Every strategy needs credentials, an SDK client, and a loop:

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

client_id    = "{{CLIENT_ID}}"
access_token = "{{ACCESS_TOKEN}}"

dhan = dhanhq(DhanContext(client_id, access_token))

while True:
    # your trading logic here
    time.sleep(60)
```

---

## Pine Script to Python

AI-powered converter that translates TradingView Pine Script v5 strategies into Python code for Dhan Cloud.

Dhan Cloud includes an AI-powered converter that translates TradingView Pine Script v5 strategies into Python code compatible with Dhan Cloud.

> **note:** Only Pine Script **v5** is supported. Paste the full script including the `//@version=5` header.

The converter uses a combination of fixed mapping rules and generative AI. Output code is a starting point, not production-ready. Always review the generated code before deploying with real funds.

## How to Use It

1. Click **New Strategy** and select **Pine Script to Python**
2. Paste your Pine Script v5 strategy
3. The converter maps indicators, conditions, and entry/exit logic to Python equivalents
4. Review the output, set your Variables and Dependencies, then deploy

## What Gets Converted

| Pine Script | Python equivalent |
|---|---|
| `ta.ema(close, 20)` | `pandas_ta.ema(df['close'], 20)` |
| `strategy.entry("Long", strategy.long)` | `dhan.place_order(..., transaction_type=dhan.BUY)` |
| `strategy.close("Long")` | `dhan.place_order(..., transaction_type=dhan.SELL)` |
| `request.security(...)` | `dhan.intraday_minute_data(...)` or `dhan.historical_daily_data(...)` |

## Limitations

- `strategy.risk.*` functions have no direct Python equivalent. The AI will approximate or omit them.
- Multi-timeframe logic may need manual adjustment after conversion.
- Replay and backtesting are not converted. Dhan Cloud runs strategies live only.
- Custom Pine Script functions are converted on a best-effort basis and should be tested carefully.

## Example

**Input Pine Script:**

```pinescript
//@version=5
strategy("EMA Crossover", overlay=true)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")
```

**Generated Python:**

```python
from dhanhq import DhanContext, dhanhq
import pandas as pd
import pandas_ta as ta
import time

client_id    = "{{CLIENT_ID}}"
access_token = "{{ACCESS_TOKEN}}"
dhan = dhanhq(DhanContext(client_id, access_token))

def run():
    from datetime import date, timedelta
    to_date   = date.today().isoformat()
    from_date = (date.today() - timedelta(days=5)).isoformat()
    resp = dhan.intraday_minute_data(
        security_id="13", exchange_segment="IDX_I",
        instrument_type="INDEX", from_date=from_date, to_date=to_date
    )
    df = pd.DataFrame(resp.get("data", []))
    df['fast'] = ta.ema(df['close'], length=9)
    df['slow'] = ta.ema(df['close'], length=21)

    crossover  = df['fast'].iloc[-2] < df['slow'].iloc[-2] and df['fast'].iloc[-1] > df['slow'].iloc[-1]
    crossunder = df['fast'].iloc[-2] > df['slow'].iloc[-2] and df['fast'].iloc[-1] < df['slow'].iloc[-1]

    if crossover:
        dhan.place_order(security_id="1333", exchange_segment=dhan.NSE,
                         transaction_type=dhan.BUY, quantity=1,
                         order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
    elif crossunder:
        dhan.place_order(security_id="1333", exchange_segment=dhan.NSE,
                         transaction_type=dhan.SELL, quantity=1,
                         order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)

while True:
    run()
    time.sleep(60)
```

> **warning:** Always review AI-generated code before deploying with real funds. Verify order quantities, product types, and exit conditions match your intended logic.

---

## First Query

Run your first interaction with Dhan MCP.

Once installed, try asking your AI client:

> "What are my available funds?"

The AI calls `portfolio_agent_tool`, fetches your live account data, and presents it:

```
Your available funds:
- Cash available: ₹1,24,500
- Margin used: ₹45,000
- Margin available: ₹79,500
```

No code. No manual API calls. Just a question and a live answer.

---

## Try more

- *"Show me my holdings"*
- *"What's the current price of RELIANCE?"*
- *"How much margin do I need to buy 10 INFY intraday?"*
- *"Place a limit buy for 5 HDFCBANK at ₹1650, delivery"* (places a real order with confirmation)

---

## Installation

Set up Dhan MCP with your preferred AI client.

Select your AI client and follow the instructions below.


### Claude Web

1. Go to [Claude.ai](https://claude.ai) and open **Settings** → **Connectors** → **Customize**
2. Tap the **+** button beside the search bar and choose **Add Custom Connector**
3. Set the name to **Dhan** and enter the MCP URL:

```
https://mcp.dhan.co/mcp
```

4. Hit **Connect** and finish the Dhan authentication flow
5. Dhan tools will now be available in your Claude conversations

This connector also syncs to Claude Desktop and Claude CLI. Restart them if tools don't appear right away.

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Claude Code

1. Install Claude Code CLI if you haven't already — see the [official docs](https://docs.anthropic.com/en/docs/claude-code)
2. Run the following in your terminal:

```bash
claude mcp add --transport http dhan https://mcp.dhan.co/mcp
```

3. Launch Claude Code by typing `claude` in your terminal
4. Enter `/mcp` and pick **dhan** from the list
5. Choose **Authenticate** and hit Enter — your browser will open for Dhan login
6. Complete sign-in with your Dhan credentials. You'll land on a confirmation page
7. Back in the terminal, run `/mcp` again to confirm the status is connected

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### ChatGPT

A native Dhan integration for ChatGPT is on the way. For now, connect manually via developer mode.

1. In ChatGPT, tap your profile icon (bottom left), then head to **Settings** → **Apps**
2. Open **Advanced Settings** and turn on **Developer Mode**
3. With that enabled, tap **Create App** at the top of the popup (beside the back button)
4. Enter the name as **Dhan**, set authentication to **OAuth**, and add the MCP URL:

```
https://mcp.dhan.co/mcp
```

5. Confirm by clicking **Create** after acknowledging *I understand*
6. When prompted to add Dhan MCP, toggle on **Referencing Memories** for richer responses, then tap **Sign In**
7. Authenticate on the Dhan login page — you'll be redirected back to ChatGPT afterward
8. Open a new chat and try the verification prompt below

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Codex

1. Install the Codex CLI if needed — see the [official repo](https://github.com/openai/codex)
2. Run this command in your terminal:

```bash
codex mcp add dhan --url https://mcp.dhan.co/mcp
```

3. Your browser will open for Dhan authentication — sign in and setup completes automatically
4. Launch Codex by typing `codex` in your terminal
5. Enter `/mcp` to confirm the Dhan server shows as connected

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Cursor

1. In Cursor, open **Settings** (beside your profile in the bottom left)
2. Navigate to **Tools & MCPs** in the left sidebar
3. Click **New MCP Server** under Home MCP Servers — a config file will open in the editor
4. Paste the following and save (Cmd+S / Ctrl+S):

```json
{
  "mcpServers": {
    "dhan": {
      "url": "https://mcp.dhan.co/mcp"
    }
  }
}
```

5. Dhan will appear in your MCP servers list. Click **Connect** to launch the auth page
6. Log in with your Dhan credentials — you'll be taken back to Cursor with a connected status
7. Return to the chat and begin a new conversation

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### OpenCode

Download [OpenCode](https://opencode.ai/download) if not already installed. Install the terminal version first — once connected, you can also use it with OpenCode Desktop.

1. In your terminal, run `opencode mcp add` and follow the prompts:
   - **Enter MCP server name:** `dhan`
   - **Select MCP server type:** Remote
   - **Enter MCP server URL:** `https://mcp.dhan.co/mcp`
   - **Does this server require OAuth authentication:** Yes
   - **Do you have a pre-registered client ID:** No

2. Run the following command to authenticate:

```bash
opencode mcp auth dhan
```

3. This will open the Dhan OAuth page in your browser — sign in to complete authentication

4. Open OpenCode by typing `opencode` in your terminal and type `/mcp` to verify the Dhan server is connected

This will also add the MCP server to your OpenCode Desktop application. Restart OpenCode Desktop if the server is not immediately visible.

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Custom

For any client that supports MCP, use these connection details:

- **Name:** Dhan
- **Authentication:** OAuth
- **MCP URL:**

```
https://mcp.dhan.co/mcp
```

Authentication uses OAuth. When your client requests login, you'll be directed to Dhan to sign in with your account.

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP


## Prerequisites

- An active Dhan account with trading access
- Data API subscription (optional, needed only for live market quotes and option chains)

## Verify the connection

After setup, ask your AI client:

> "What tools do you have from Dhan?"

It should list the available tools: portfolio, orders, trading, market data, historical data, margin, alerts, and search.

---

## Requirements

What you need before connecting to Dhan MCP.

| Requirement | Needed for |
|-------------|-----------|
| Dhan trading account | Everything |
| Node.js v18+ | Running the MCP transport |
| MCP-compatible client | Interacting with the server |
| Data API subscription (optional) | Live quotes, option chains |

## Node.js

```bash
# macOS (Homebrew)
brew install node

# Windows (winget)
winget install OpenJS.NodeJS

# Verify
node --version
npx --version
```

## Compatible clients

- [Claude Desktop](https://claude.ai/download)
- [Cursor](https://cursor.com)
- [Kiro](https://kiro.dev)
- VS Code with MCP extensions
- Any custom application built on an MCP SDK

---

## Dhan MCP

Connect your live Dhan trading account to any MCP-compatible AI client — trade, manage portfolio, fetch market data, set alerts, and calculate margins through natural language.

**A Model Context Protocol server for live trading on Indian exchanges.**

Dhan MCP connects your authenticated Dhan trading account to any MCP-compatible AI client. Trade equities and F&O, manage your portfolio, fetch market data, set alerts, and calculate margins — entirely through natural language.

Built on the open [Model Context Protocol](https://modelcontextprotocol.io) standard, Dhan MCP works with Claude Desktop, Cursor, OpenCode, Kiro, VS Code, and any other client that speaks MCP.

---

## How it works


**Flow:** You → MCP Client → mcp.dhan.co → DEXT → Exchange

1. **You** — Give a natural language instruction (e.g. "Show my holdings", "Place a buy order")
2. **MCP Client** — Claude, Cursor, Kiro, or another MCP client interprets intent and selects a tool
3. **mcp.dhan.co** — Dhan MCP Server converts the tool call into the correct API action
4. **DEXT** — Dhan internal infrastructure handles routing, validation, and service communication
5. **Exchange** — Request is routed to NSE, BSE, or MCX


---

## Connect your client


Select your AI client and follow the instructions below.


### Claude Web

1. Go to [Claude.ai](https://claude.ai) and open **Settings** → **Connectors** → **Customize**
2. Tap the **+** button beside the search bar and choose **Add Custom Connector**
3. Set the name to **Dhan** and enter the MCP URL:

```
https://mcp.dhan.co/mcp
```

4. Hit **Connect** and finish the Dhan authentication flow
5. Dhan tools will now be available in your Claude conversations

This connector also syncs to Claude Desktop and Claude CLI. Restart them if tools don't appear right away.

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Claude Code

1. Install Claude Code CLI if you haven't already — see the [official docs](https://docs.anthropic.com/en/docs/claude-code)
2. Run the following in your terminal:

```bash
claude mcp add --transport http dhan https://mcp.dhan.co/mcp
```

3. Launch Claude Code by typing `claude` in your terminal
4. Enter `/mcp` and pick **dhan** from the list
5. Choose **Authenticate** and hit Enter — your browser will open for Dhan login
6. Complete sign-in with your Dhan credentials. You'll land on a confirmation page
7. Back in the terminal, run `/mcp` again to confirm the status is connected

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### ChatGPT

A native Dhan integration for ChatGPT is on the way. For now, connect manually via developer mode.

1. In ChatGPT, tap your profile icon (bottom left), then head to **Settings** → **Apps**
2. Open **Advanced Settings** and turn on **Developer Mode**
3. With that enabled, tap **Create App** at the top of the popup (beside the back button)
4. Enter the name as **Dhan**, set authentication to **OAuth**, and add the MCP URL:

```
https://mcp.dhan.co/mcp
```

5. Confirm by clicking **Create** after acknowledging *I understand*
6. When prompted to add Dhan MCP, toggle on **Referencing Memories** for richer responses, then tap **Sign In**
7. Authenticate on the Dhan login page — you'll be redirected back to ChatGPT afterward
8. Open a new chat and try the verification prompt below

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Codex

1. Install the Codex CLI if needed — see the [official repo](https://github.com/openai/codex)
2. Run this command in your terminal:

```bash
codex mcp add dhan --url https://mcp.dhan.co/mcp
```

3. Your browser will open for Dhan authentication — sign in and setup completes automatically
4. Launch Codex by typing `codex` in your terminal
5. Enter `/mcp` to confirm the Dhan server shows as connected

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Cursor

1. In Cursor, open **Settings** (beside your profile in the bottom left)
2. Navigate to **Tools & MCPs** in the left sidebar
3. Click **New MCP Server** under Home MCP Servers — a config file will open in the editor
4. Paste the following and save (Cmd+S / Ctrl+S):

```json
{
  "mcpServers": {
    "dhan": {
      "url": "https://mcp.dhan.co/mcp"
    }
  }
}
```

5. Dhan will appear in your MCP servers list. Click **Connect** to launch the auth page
6. Log in with your Dhan credentials — you'll be taken back to Cursor with a connected status
7. Return to the chat and begin a new conversation

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### OpenCode

Download [OpenCode](https://opencode.ai/download) if not already installed. Install the terminal version first — once connected, you can also use it with OpenCode Desktop.

1. In your terminal, run `opencode mcp add` and follow the prompts:
   - **Enter MCP server name:** `dhan`
   - **Select MCP server type:** Remote
   - **Enter MCP server URL:** `https://mcp.dhan.co/mcp`
   - **Does this server require OAuth authentication:** Yes
   - **Do you have a pre-registered client ID:** No

2. Run the following command to authenticate:

```bash
opencode mcp auth dhan
```

3. This will open the Dhan OAuth page in your browser — sign in to complete authentication

4. Open OpenCode by typing `opencode` in your terminal and type `/mcp` to verify the Dhan server is connected

This will also add the MCP server to your OpenCode Desktop application. Restart OpenCode Desktop if the server is not immediately visible.

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP

### Custom

For any client that supports MCP, use these connection details:

- **Name:** Dhan
- **Authentication:** OAuth
- **MCP URL:**

```
https://mcp.dhan.co/mcp
```

Authentication uses OAuth. When your client requests login, you'll be directed to Dhan to sign in with your account.

Once set up, verify the connection with this prompt:

> Check my holdings with Dhan MCP


---

## What you can do

| Capability | Description |
|-----------|-------------|
| **Portfolio** | Check funds, holdings, positions, and today's trades |
| **Orders** | Place, modify, and cancel orders — including Super Orders |
| **Market data** | Live prices, quotes with depth, option chains |
| **Historical data** | OHLCV candles across multiple timeframes |
| **Margin** | Pre-order margin checks for single or basket orders |
| **Alerts** | Price and indicator-triggered alerts with linked orders |
| **Search** | Resolve company names and tickers to Dhan security IDs |

---

## Next steps

- [What is MCP?](/mcp/overview/what-is-mcp) — Understand the protocol standard
- [Architecture](/mcp/overview/architecture) — How Dhan MCP fits into the ecosystem
- [Installation](/mcp/getting-started/installation) — Client-specific setup details
- [Tools](/mcp/tools/portfolio) — Full tool documentation
- [REST APIs](/api/v2/) — HTTP API reference
- [Agent Skills](/skills/) — AI-agent skill pack for coding agents
- [Developer Portal](https://developer.dhanhq.co) — Manage your API access

---

## Architecture

How Dhan MCP connects your AI client to your live trading account through the Model Context Protocol.

# Dhan MCP Architecture Flow

This diagram shows how a developer can interact with Dhan's trading infrastructure using natural language through an MCP-enabled client.


**Flow:** You → MCP Client → mcp.dhan.co → DEXT → Exchange

1. **You** — Give a natural language instruction (e.g. "Show my holdings", "Place a buy order")
2. **MCP Client** — Claude, Cursor, Kiro, or another MCP client interprets intent and selects a tool
3. **mcp.dhan.co** — Dhan MCP Server converts the tool call into the correct API action
4. **DEXT** — Dhan internal infrastructure handles routing, validation, and service communication
5. **Exchange** — Request is routed to NSE, BSE, or MCX


---

## 1. You

The developer gives a natural language instruction, such as:

- "Show my holdings"
- "Place a buy order"
- "Get NIFTY option chain"

This starts the workflow.

---

## 2. MCP Client

The instruction is sent to an MCP-compatible client such as Claude, Cursor, or Kiro.

The client understands the user's intent and decides which tool needs to be called.

---

## 3. Tool Call to mcp.dhan.co

The MCP Client sends a structured tool call to `mcp.dhan.co`.

This acts as the Dhan MCP Server.

---

## 4. Dhan MCP Server

The MCP Server exposes Dhan's trading tools and capabilities through the MCP protocol.

It converts the client's request into the correct backend/API action.

---

## 5. DEXT

The request is passed to Dhan's internal infrastructure, shown as DEXT.

This layer handles routing, validation, and communication with trading services.

---

## 6. Exchange

Finally, the request is routed to the relevant exchange:

- NSE
- BSE
- MCX

The exchange processes the trading-related request.

---

## Simple Flow

**You → MCP Client → mcp.dhan.co → DEXT → Exchange**

---

## What is MCP?

The Model Context Protocol is an open standard that connects AI applications to external tools and data sources through a universal interface.

The **Model Context Protocol (MCP)** is an open standard that defines how AI applications connect to external tools, data sources, and services. It provides a universal interface — so instead of building custom integrations for every AI model and every API, you build one MCP server and it works with any compatible client.

Think of it as a standardized connector between AI and the outside world.

---

## The problem MCP solves

Without MCP, every AI application needs bespoke code to talk to each external service. If you want Claude, ChatGPT, Cursor, and Kiro to all access your trading account, you'd traditionally need four separate integrations.

MCP eliminates this. You build one server, and any MCP-compatible client can connect to it immediately.

---

## How MCP works

MCP uses a client-server architecture:

- **MCP Client** (Host) — The AI application you interact with. Claude Desktop, Cursor, Kiro, VS Code, and many others act as MCP clients.
- **MCP Server** — A service that exposes capabilities (tools, resources, prompts) over the MCP protocol. Dhan MCP is one such server.
- **Protocol** — The standardized communication layer between client and server. Handles tool discovery, invocation, and response formatting.

When you connect a client to a server:

1. The client discovers what tools the server offers
2. When you ask a question, the AI decides which tool to call
3. The client sends the tool call to the server
4. The server executes it and returns the result
5. The AI incorporates the result into its response

---

## Why MCP for trading?

Trading requires real-time data, authenticated access, and careful execution. MCP is well-suited because:

- **Scoped authentication** — Your session stays on the server. No tokens in config files.
- **Tool-level granularity** — Each capability (place order, check margin, fetch quotes) is a discrete tool the AI can invoke.
- **Confirmation flows** — The AI shows you order details before submitting. You stay in control.
- **Client-agnostic** — Switch between Claude, Cursor, or any other client without reconfiguring your trading access.

---

## The standard

MCP was originally developed by [Anthropic](https://www.anthropic.com) and released as an open standard. It has since been adopted by a broad ecosystem of AI tools and agent platforms.

The full specification and documentation are available at [modelcontextprotocol.io](https://modelcontextprotocol.io).

---

## Next

- [Architecture](/mcp/overview/architecture) — How Dhan MCP implements the protocol
- [Installation](/mcp/getting-started/installation) — Connect your first client

---

## Alerts

Create price or indicator-triggered alerts with linked orders.

**Tool:** `alerts_agent_tool`

> **Equities Only:** Supports **equities and indices only**. F&O, commodity, and currency are not supported.

Create price or indicator-triggered alerts with a linked order that fires automatically when the condition is met.

---

## Example prompts

- *"Create an alert: if RELIANCE crosses ₹1400 on the 1-min chart, place a LIMIT BUY at ₹1405 for 5 shares intraday."*
- *"Show all my active alerts."*
- *"Delete alert 789..."*

---

## Supported conditions

**Condition types:** price vs a fixed value, technical indicator vs a fixed value, one indicator vs another, indicator vs previous close.

**Operators:** crossing up, crossing down, greater than, less than, equal.

**Timeframes:** day, 1-min, 5-min, 15-min.

---

## Margin

Check required margin before placing any order — single or basket.

**Tool:** `margin_agent_tool`

Check required margin before placing any order — single or basket.

---

## Example prompts

- *"What margin do I need to buy 10 RELIANCE at ₹1350 intraday?"*
- *"Calculate basket margin for buying 5 RELIANCE and selling 2 POWERGRID simultaneously."*

---

## Market Data

Fetch live prices, quotes, option chains, and historical OHLCV candles.

Access real-time and historical market data for equities, F&O, and indices.

---

## Live Market Data

**Tool:** `market_data_agent_tool`

> **Data API Required:** Requires an active **Dhan Data API subscription**. Without it, all actions return Unauthorized.

Fetch live prices, full quotes with order book depth, and option chains.

**Example prompts:**
- *"What's the current LTP for RELIANCE and INFY?"*
- *"Get the full quote with bid/ask depth for HDFCBANK."*
- *"Show me the option chain for NIFTY expiring 26 June 2026."*
- *"What expiry dates are available for BANKNIFTY?"*

---

## Historical Data

**Tool:** `historical_data_agent_tool`

Fetch OHLCV candles across multiple timeframes.

**Example prompts:**
- *"Show 5-minute candles for RELIANCE on 21 May 2026."*
- *"Get daily OHLCV for POWERGRID from 1 Jan to 22 May 2026."*
- *"Fetch 1-hour candles for UCOBANK for the last 30 days."*

**Supported intraday intervals:** `1`, `5`, `15`, `30`, `60` minutes.

---

## Orders

View, place, modify, and cancel orders — including Super Orders.

Manage the full order lifecycle — view your order book, check trade fills, and place or modify live orders.

---

## Order Book

**Tool:** `orderbook_agent_tool`

View and track orders — pending, executed, cancelled, or rejected.

**Example prompts:**
- *"Show all my orders for today including rejected ones."*
- *"Get full details of order 221260522781103 including the rejection reason."*
- *"Show my super order book with all legs."*

---

## Trade Book

**Tool:** `tradebook_agent_tool`

View all fills executed today.

**Example prompts:**
- *"Show all trades executed today."*
- *"Show me all fills for order 123..."*

---

## Trading

**Tool:** `trading_agent_tool`

> **Live Orders:** These place **real orders** on your live Dhan account. The assistant always shows you the full order details before submitting and runs a pre-trade margin check by default.

Place, modify, and cancel orders — including Super Orders.

**Example prompts:**
- *"Place a limit BUY for 10 INFY at ₹1800, intraday, DAY."*
- *"Modify order 123... to ₹1810."*
- *"Cancel order 123..."*
- *"Place a super order: buy RELIANCE at ₹1350, target ₹1400, stop-loss ₹1310, trailing jump ₹5, intraday."*
- *"Move the target leg of super order 456... to ₹1420."*
- *"Cancel the stop-loss leg of super order 456..."*

---

## Portfolio

Check your account snapshot — funds, holdings, positions, and today's trades.

**Tool:** `portfolio_agent_tool`

Check your account snapshot at any time — funds, holdings, positions, and executed trades.

---

## Example prompts

- *"What are my available funds and margin utilization?"*
- *"Show all my holdings with invested value."*
- *"What are my open positions and their P&L?"*
- *"Did I execute any trades today?"*

---

## Search

Resolve company names, tickers, and indices to Dhan security IDs.

**Tool:** `search_agent_tool`

Resolve any company name, ticker, or index to its Dhan security ID. Always use the security ID when placing orders.

---

## Example prompts

- *"What is the security ID for HDFCBANK on NSE?"*
- *"Find all RELIANCE derivatives expiring in May 2026."*

---

## Tips

Pass the exchange (`NSE`, `BSE`, or `MCX`) to narrow results when a name matches multiple instruments.
