Dhan Reference

class aio_trader.dhan.Dhan(client_id: str, access_token: str)

Bases: AbstractBroker

Unofficial Dhan Class to interact with REST APIs

Parameters:
  • client_id (str) – Dhan client id

  • access_token (str) – Dhan access token

async authorize(**_)

Not required can be skipped

async cancel_forever(order_id) dict

Delete Forever orders using the order id of an order.

Parameters:

order_id (str) – Order id

async cancel_order(order_id: str) dict

Cancel a pending order in the orderbook using the order ID.

Parameters:

order_id (str) – The ID of the order to cancel.

async convert_position(from_product_type, exchange_segment, position_type, security_id, convert_qty, to_product_type) dict

Convert Position from Intraday to Delivery or vice versa.

Parameters:
  • from_product_type (str) – The product type to convert from (e.g., CNC).

  • exchange_segment (str) – The exchange segment (e.g., NSE_EQ).

  • position_type (str) – The type of position (e.g., LONG).

  • security_id (str) – The ID of the security to convert.

  • convert_qty (int) – The quantity to convert.

  • to_product_type (str) – The product type to convert to (e.g., CNC).

convert_to_date_time(epoch) datetime

Convert EPOCH time to Python datetime object in IST.

Parameters:

epoch (int) – The EPOCH time to convert.

async edis_inquiry(isin) dict

Inquire about the eDIS status of the provided ISIN.

Parameters:

isin (str) – The ISIN to inquire about.

async expiry_list(under_security_id, under_exchange_segment) dict

Retrieve the dates of all expiries for a specified underlying instrument.

Parameters:
  • under_security_id (int) – The security ID of the underlying instrument.

  • under_exchange_segment (str) – The exchange segment of the underlying instrument (e.g., NSE, BSE).

async fetch_security_list(mode: Literal['compact', 'detailed'] = 'compact') bytes

Fetch CSV file from dhan based on the specified mode and save it to the current directory.

Parameters:

mode (Literal["compact", "detailed"]) – The mode to fetch the CSV (‘compact’ or ‘detailed’).

async generate_tpin() dict

Generate T-Pin on registered mobile number.

async get_forever() list

Retrieve a list of all existing Forever Orders.

async get_fund_limits() dict

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

async get_holdings() dict

Retrieve all holdings bought/sold in previous trading sessions.

async get_order_by_correlationID(correlationID) dict

Retrieve the order status using a field called correlation ID.

Parameters:

corelationID (str) – The correlation ID provided during order placement.

async get_order_by_id(order_id) dict

Retrieve the details and status of an order from the orderbook placed during the day.

Parameters:

order_id (str) – The ID of the order to retrieve.

async get_order_list() dict

Retrieve a list of all orders requested in a day with their last updated status.

async get_positions() dict

Retrieve a list of all open positions for the day.

async get_trade_book(order_id=None) dict

Retrieve a list of all trades executed in a day.

Parameters:

order_id (str, optional) – The ID of the specific order to retrieve trades for.

async get_trade_history(from_date, to_date, page_number=0) dict

Retrieve the trade history for a specific date range.

Parameters:
  • from_date (str) – The start date for the trade history.

  • to_date (str) – The end date for the trade history.

  • page_number (int) – The page number for pagination.

async historical_daily_data(security_id, exchange_segment, instrument_type, from_date, to_date, expiry_code=0) dict

Retrieve OHLC & Volume of daily candle for desired instrument.

Parameters:
  • security_id (str) – Security ID of the instrument.

  • exchange_segment (str) – The exchange segment (e.g., NSE, BSE).

  • instrument_type (str) – The type of instrument (e.g., stock, option).

  • expiry_code (str) – The expiry code for derivatives.

  • from_date (str) – The start date for the historical data.

  • to_date (str) – The end date for the historical data.

Raises:

ValueError – if expiry_code not one of 0, 1, 2 ,``3``

async intraday_minute_data(security_id, exchange_segment, instrument_type, from_date, to_date, interval=1) dict

Retrieve OHLC & Volume of minute candles for desired instrument for last 5 trading day.

Parameters:
  • security_id (str) – The ID of the security.

  • exchange_segment (str) – The exchange segment (e.g., NSE, BSE).

  • instrument_type (str) – The type of instrument (e.g., stock, option).

Raises:

ValueError – if interval not one of 1, 5, 15, 25, 60

async kill_switch(action: Literal['activate', 'deactivate']) dict

Control kill switch for user, which will disable trading for current trading day.

Parameters:

action (Literal['activate', "deactivate"]) – ‘activate’ or ‘deactivate’ to control the kill switch.

async ledger_report(from_date, to_date) dict

Retrieve the ledger details for a specific date range.

Parameters:
  • from_date (str) – The start date for the trade history.

  • to_date (str) – The end date for the trade history.

async margin_calculator(security_id, exchange_segment, transaction_type, quantity, product_type, price, trigger_price=0) dict

Calculate the margin required for a trade based on the provided parameters.

Parameters:
  • security_id (str) – The ID of the security for which the margin is to be calculated.

  • exchange_segment (str) – The exchange segment (e.g., NSE_EQ) where the trade will be executed.

  • transaction_type (str) – The type of transaction (BUY/SELL).

  • quantity (int) – The quantity of the security to be traded.

  • product_type (str) – The product type (e.g., CNC, INTRA) of the trade.

  • price (float) – The price at which the trade will be executed.

  • trigger_price (float) – The trigger price for the trade. Defaults to 0.

async modify_forever(order_id, order_flag, order_type, leg_name, quantity, price, trigger_price, disclosed_quantity, validity) dict

Modify a forever order based on the specified leg name. The variables that can be modified include price, quantity, order type, and validity.

Parameters:
  • order_id (str) – The ID of the order to modify.

  • order_flag (str) – The order flag indicating the type of order (e.g., SINGLE, OCO).

  • order_type (str) – The type of order (e.g., LIMIT, MARKET).

  • leg_name (str) – The name of the leg to modify.

  • quantity (int) – The new quantity for the order.

  • price (float) – The new price for the order.

  • trigger_price (float) – The trigger price for the order.

  • disclosed_quantity (int) – The disclosed quantity for the order.

  • validity (str) – The validity of the order.

async modify_order(order_id, order_type, leg_name, quantity, price, trigger_price, disclosed_quantity, validity) dict

Modify a pending order in the orderbook.

Parameters:
  • order_id (str) – The ID of the order to modify.

  • order_type (str) – The type of order (e.g., LIMIT, MARKET).

  • leg_name (str) – The name of the leg to modify.

  • quantity (str) – The new quantity for the order.

  • price (float) – The new price for the order.

  • trigger_price (float) – The trigger price for the order.

  • disclosed_quantity (int) – The disclosed quantity for the order.

  • validity (str) – The validity of the order.

async ohlc_data(securities) dict

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

Parameters:

securities (dict) – A dictionary where keys are exchange segments and values are lists of security IDs.

async open_browser_for_tpin(isin, qty, exchange, segment='EQ', bulk=False) dict

Opens the default web browser to enter T-Pin.

Parameters:
  • isin (str) – The ISIN of the security.

  • qty (int) – The quantity of the security.

  • exchange (str) – The exchange where the security is listed.

  • segment (str) – The segment of the exchange (default is ‘EQ’).

  • bulk (bool) – Flag for bulk operations (default is False).

async option_chain(under_security_id, under_exchange_segment, expiry) dict

Retrieve the real-time Option Chain for a specified underlying instrument.

Parameters:
  • under_security_id (int) – The security ID of the underlying instrument.

  • under_exchange_segment (str) – The exchange segment of the underlying instrument (e.g., NSE, BSE).

  • expiry (str) – The expiry date of the options.

async place_forever(security_id, exchange_segment, transaction_type, product_type, order_type, quantity, price, trigger_Price, order_flag='SINGLE', disclosed_quantity=0, validity='DAY', price1=0, trigger_Price1=0, quantity1=0, tag=None, symbol='') dict

Place a new forever order in the Dhan account.

Parameters:
  • security_id (str) – The ID of the security to trade.

  • exchange_segment (str) – The exchange segment (e.g., NSE, BSE).

  • transaction_type (str) – The type of transaction (BUY/SELL).

  • product_type (str) – The product type (e.g., CNC, INTRA).

  • order_type (str) – The type of order (LIMIT, MARKET, etc.).

  • quantity (int) – The quantity of the order.

  • price (float) – The price of the order.

  • trigger_Price (float) – The trigger price for the order.

  • order_flag (str) – The order flag (default is “SINGLE”).

  • disclosed_quantity (int) – The disclosed quantity for the order.

  • validity (str) – The validity of the order (DAY, IOC, etc.).

  • price1 (float) – The secondary price for the order.

  • trigger_Price1 (float) – The secondary trigger price for the order.

  • quantity1 (int) – The secondary quantity for the order.

  • tag (str) – Optional correlation ID for tracking.

  • symbol (str) – The trading symbol for the order.

async place_order(security_id, exchange_segment, transaction_type, quantity, order_type, product_type, price, trigger_price=0, disclosed_quantity=0, after_market_order=False, validity='DAY', amo_time='OPEN', bo_profit_value=None, bo_stop_loss_Value=None, tag=None) dict

Place a new order in the Dhan account.

Parameters:
  • security_id (str) – The ID of the security to trade.

  • exchange_segment (str) – The exchange segment (e.g., NSE, BSE).

  • transaction_type (str) – The type of transaction (BUY/SELL).

  • quantity (int) – The quantity of the order.

  • order_type (str) – The type of order (LIMIT, MARKET, etc.).

  • product_type (str) – The product type (CNC, INTRA, etc.).

  • price (float) – The price of the order.

  • trigger_price (float) – The trigger price for the order.

  • disclosed_quantity (int) – The disclosed quantity for the order.

  • after_market_order (bool) – Flag for after market order.

  • validity (str) – The validity of the order (DAY, IOC, etc.).

  • amo_time (str) – The time for AMO orders.

  • bo_profit_value (float) – The profit value for BO orders.

  • bo_stop_loss_Value (float) – The stop loss value for BO orders.

  • tag (str) – Optional correlation ID for tracking.

Raises:

ValueError – if amo_time not one of PRE_OPEN, OPEN, OPEN_30, OPEN_60

async place_slice_order(security_id, exchange_segment, transaction_type, quantity, order_type, product_type, price, trigger_price=0, disclosed_quantity=0, after_market_order=False, validity='DAY', amo_time='OPEN', bo_profit_value=None, bo_stop_loss_Value=None, tag=None) dict

Place a new slice order in the Dhan account.

Parameters:
  • security_id (str) – The ID of the security to trade.

  • exchange_segment (str) – The exchange segment (e.g., NSE, BSE).

  • transaction_type (str) – The type of transaction (BUY/SELL).

  • quantity (int) – The quantity of the order.

  • order_type (str) – The type of order (LIMIT, MARKET, etc.).

  • product_type (str) – The product type (CNC, MIS, etc.).

  • price (float) – The price of the order.

  • trigger_price (float) – The trigger price for the order.

  • disclosed_quantity (int) – The disclosed quantity for the order.

  • after_market_order (bool) – Flag for after market order.

  • validity (str) – The validity of the order (DAY, IOC, etc.).

  • amo_time (str) – The time for AMO orders.

  • bo_profit_value (float) – The profit value for BO orders.

  • bo_stop_loss_Value (float) – The stop loss value for BO orders.

  • tag (str) – Optional correlation ID for tracking.

Raises:

ValueError – if amo_time not one of OPEN, OPEN_30, OPEN_60

async quote_data(securities) dict

Retrieve full details including market depth, OHLC data, OI and volume along with LTP for specified instruments.

Parameters:

securities (dict) – A dictionary where keys are exchange segments and values are lists of security IDs.

async ticker_data(securities) dict

Retrieve the latest market price for specified instruments.

Parameters:

securities (dict) – A dictionary where keys are exchange segments and values are lists of security IDs.

class aio_trader.dhan.DhanFeed(client_id, access_token, parse_data: bool = True, session: ClientSession | None = None)

Bases: AbstractFeeder

Websocket class for Dhan

Only supports v2 of the API

property on_tick: Callable[[DhanFeed, Dict[str, Any], bool], None]

A user defined function that receives the tick data as a dict and a bool value indicating if the message is parsed.

def on_tick(feed: DhanFeed, tick: Dict[str, Any], binary=False) -> None

property on_connect: Callable[[DhanFeed], None]

A user defined function called when a websocket connection is opened.

def on_connect(feed: DhanFeed) -> None

Parameters:
  • client_id (str) – Dhan client id

  • access_token (str) – Dhan access token

  • parse_data (bool) – If true, on_tick handler receives raw binary/text data. Default True.

  • session (Optional[aiohttp.ClientSession].) – Client Session for making HTTP requests.

async close()

Perform clean up operations to gracefully exit

async connect(**kwargs) None

Connect and start the Websocket connection

Uses the retry decorator. Reconnects in case of error @retry(max_retries=5, base_wait=2, max_wait=60)

Parameters:

kwargs – Any keyword arguments to pass to aiohttp.ClientSession.ws_connect

Type:

kwargs: Any

async subscribe(symbols: List[Tuple]) None

Subscribe to live market feeds.

Parameters:

symbols (List[Tuple]) – List of instruments to subscribe

Structure for subscribing is (exchange_segment, “security_id”, subscription_type)

symbols = [
    (DhanFeed.NSE, "1333", DhanFeed.Ticker),   # Ticker - Ticker Data
    (DhanFeed.NSE, "1333", DhanFeed.Quote),     # Quote - Quote Data
    (DhanFeed.NSE, "1333", DhanFeed.Full),      # Full - Full Packet
    (DhanFeed.NSE, "11915", DhanFeed.Depth),
]
subscribe_symbols(symbols: List[Tuple])

Function to subscribe to additional symbols when connection is already established.

Parameters:

symbols (List[Tuple]) – List of instruments to subscribe

Structure for subscribing is (exchange_segment, “security_id”, subscription_type)

instruments = [
    (DhanFeed.NSE, "1333", DhanFeed.Ticker),   # Ticker - Ticker Data
    (DhanFeed.NSE, "1333", DhanFeed.Quote),     # Quote - Quote Data
    (DhanFeed.NSE, "1333", DhanFeed.Full),      # Full - Full Packet
    (DhanFeed.NSE, "11915", DhanFeed.Depth),
]
async unsubscribe_symbols(symbols: List[Tuple]) None

Unsubscribe from live market feed.

instruments = [
    (DhanFeed.NSE, "1333", DhanFeed.Ticker),   # Ticker - Ticker Data
    (DhanFeed.NSE, "1333", DhanFeed.Quote),     # Quote - Quote Data
    (DhanFeed.NSE, "1333", DhanFeed.Full),      # Full - Full Packet
    (DhanFeed.NSE, "11915", DhanFeed.Depth),
]
class aio_trader.dhan.DhanOrder(client_id, access_token, session: ClientSession | None, parse_data: bool = True)

Bases: AbstractFeeder

Websocket class for Dhan Order Websocket

property on_tick: Callable[[DhanOrder, Dict[str, Any], bool], None]

A user defined function called when order notification is received. Called with the order message as a dict and a bool value indicating if the order message is parsed.

Must be attached to the class to receive order updates

def on_tick(feed: DhanOrder, order: dict, binary=False) -> None

Parameters:
  • access_token (str) – Fyers access_token.

  • session (Optional[aiohttp.ClientSession].) – Client Session for making HTTP requests.

  • parse_data (bool) – If true, on_tick handler receives raw binary/text data. Default True.

async close()

Perform clean up operations to gracefully exit

async connect(**kwargs) None

Connect to websocket and process any incomming messages

Uses the retry decorator to reconnect if an error occurs @retry(max_retries=5, base_wait=2, max_wait=60)

Parameters:

kwargs – Any keyword arguments to pass to aiohttp.ClientSession.ws_connect

Type:

kwargs: Any