dhanhq


Namedhanhq JSON
Version 2.0.1 PyPI version JSON
download
home_pagehttps://dhanhq.co/
SummaryThe official Python client for communicating with the DhanHQ API
upload_time2024-11-07 06:26:36
maintainerNone
docs_urlNone
authorDhan
requires_pythonNone
licenseMIT LICENSE
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # DhanHQ-py : v2.0.0

[![PyPI](https://img.shields.io/pypi/v/dhanhq.svg)](https://pypi.org/project/dhanhq/)


The official Python client for communicating with the [Dhan API](https://api.dhan.co/v2/)  

DhanHQ-py Rest API is used to automate investing and trading. Execute orders in real time along with position management, live and historical data, tradebook and more with simple API collection.

Not just this, you also get real-time market data via DhanHQ Live Market Feed.


[Dhan](https://dhan.co) (c) 2024. Licensed under the [MIT License](https://github.com/dhan-oss/DhanHQ-py/blob/main/LICENSE)

### Documentation

- [DhanHQ Developer Kit](https://api.dhan.co/v2/)
- [DhanHQ API Documentation](https://dhanhq.co/docs/v2/)


## v2.0 - What's New

DhanHQ v2 extends execution capability with live order updates, market quotes and forever orders on superfast APIs. Some of the key highlights from this version are:
    
- Fetch LTP, Quote (with OI) and Market Depth data directly on API, for upto 1000 instruments at once with Market Quote API.

- Option Chain API which gives OI, greeks, volume, top bid/ask and price data of all strikes of a particular underlying.

- Place, modify and manage your Forever Orders, including single and OCO orders to manage risk and trade efficiently with Forever Order API.

- Order Updates are sent in real time via websockets, which will update order status of all your orders placed via any platform - `order_update`.

- Intraday Minute Data now provides OHLC with Volume data for last 5 trading days across timeframes such as 1 min, 5 min, 15 min, 25 min and 60 min - `intraday_minute_data`.

- Full Packet in Live Market Feed (`marketfeed`).

- Margin Calculator (`margin_calculator`) and Kill Switch (`kill_switch`) APIs.

### Breaking Changes

- Replaced `intraday_daily_minute_data` and `historical_minute_charts` as functions from v1.2.4

- `quantity` field needs to be placed order quantity instead of pending order quantity in Order Modification

- EPOCH time instead of Julian time in Historical Data API, and same changed for `convert_to_date_time` function

- `historical_daily_data` takes `security_id` as argument instead of `symbol`

- Nomenclature changes in `get_order_by_corelationID` to `get_order_by_correlationID`.

You can read about all other updates from DhanHQ V2 here: [DhanHQ Releases](https://dhanhq.co/docs/v2/releases/).


## Features

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

* **Live Market Feed**  
Get real-time market data to power your trading systems, with easy to implement functions and data across exchanges.

* **Market Quote**  
REST APIs based market quotes which given you snapshot of ticker mode, quote mode or full mode.

* **Option Chain**  
Single function which gives entire Option Chain across exchanges and segments, giving OI, greeks, volume, top bid/ask and price data.

* **Forever Order**  
Place, modify or delete Forever Orders, whether single or OCO to better manage your swing trades.

* **Portfolio Management**  
With this set of APIs, retrieve your holdings and positions in your portfolio as well as manage them.

* **Historical Data**  
Get historical candle data for the desired scrip across segments & exchange, both multiple minute timeframe OHLC and Daily OHLC.

* **Fund Details**  
Get all information of your trading account like balance, margin utilised, collateral, etc as well margin required for any order.

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

## Quickstart

You can install the package via pip

```
pip install dhanhq
```



### Hands-on API

```python
from dhanhq import dhanhq

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

# Place an order for Equity Cash
dhan.place_order(security_id='1333',            # HDFC Bank
    exchange_segment=dhan.NSE,
    transaction_type=dhan.BUY,
    quantity=10,
    order_type=dhan.MARKET,
    product_type=dhan.INTRA,
    price=0)
    
# Place an order for NSE Futures & Options
dhan.place_order(security_id='52175',           # Nifty PE
    exchange_segment=dhan.NSE_FNO,
    transaction_type=dhan.BUY,
    quantity=550,
    order_type=dhan.MARKET,
    product_type=dhan.INTRA,
    price=0)
  
# Fetch all orders
dhan.get_order_list()

# Get order by id
dhan.get_order_by_id(order_id)

# Modify order
dhan.modify_order(order_id, order_type, leg_name, quantity, price, trigger_price, disclosed_quantity, validity)

# Cancel order
dhan.cancel_order(order_id)

# Get order by correlation id
dhan.get_order_by_corelationID(corelationID)

# Get Instrument List
dhan.fetch_security_list("compact")

# Get positions
dhan.get_positions()

# Get holdings
dhan.get_holdings()

# Intraday Minute Data
dhan.intraday_minute_data(security_id,exchange_segment,instrument_type)

# Historical Daily Data
dhan.historical_daily_data(security_id,exchange_segment,instrument_type,expiry_code,from_date,to_date)

# Time Converter
dhan.convert_to_date_time(EPOCH Date)

# Get trade book
dhan.get_trade_book(order_id)

# Get trade history
dhan.get_trade_history(from_date,to_date,page_number=0)

# Get fund limits
dhan.get_fund_limits()

# Generate TPIN
dhan.generate_tpin()

# Enter TPIN in Form
dhan.open_browser_for_tpin(isin='INE00IN01015',
    qty=1,
    exchange='NSE')

# EDIS Status and Inquiry
dhan.edis_inquiry()

# Expiry List of Underlying
dhan.expiry_list(
    under_security_id=13,                       # Nifty
    under_exchange_segment="IDX_I"
)

# Option Chain
dhan.option_chain(
    under_security_id=13,                       # Nifty
    under_exchange_segment="IDX_I",
    expiry="2024-10-31"
)

# Market Quote Data                     # LTP - ticker_data, OHLC - ohlc_data, Full Packet - quote_data
dhan.ohlc_data(
    securities = {"NSE_EQ":[1333]}
)

# Place Forever Order (SINGLE)
dhan.place_forever(
    security_id="1333",
    exchange_segment= dhan.NSE,
    transaction_type= dhan.BUY,
    product_type=dhan.CNC,
    product_type= dhan.LIMIT,
    quantity= 10,
    price= 1900,
    trigger_Price= 1950
)
```

### Market Feed Usage
```python
from dhanhq import marketfeed

# Add your Dhan Client ID and Access Token
client_id = "Dhan Client ID"
access_token = "Access Token"

# Structure for subscribing is (exchange_segment, "security_id", subscription_type)

instruments = 
    [(marketfeed.NSE, "1333", marketfeed.Ticker),   # Ticker - Ticker Data
    (marketfeed.NSE, "1333", marketfeed.Quote),     # Quote - Quote Data
    (marketfeed.NSE, "1333", marketfeed.Full),      # Full - Full Packet
    (marketfeed.NSE, "11915", marketfeed.Ticker),
    (marketfeed.NSE, "11915", marketfeed.Full)]

version = "v2"          # Mention Version and set to latest version 'v2'

# In case subscription_type is left as blank, by default Ticker mode will be subscribed.

try:
    data = marketfeed.DhanFeed(client_id, access_token, instruments, version)
    while True:
        data.run_forever()
        response = data.get_data()
        print(response)

except Exception as e:
    print(e)

# Close Connection
data.disconnect()

# Subscribe instruments while connection is open
sub_instruments = 
    [(marketfeed.NSE, "14436", marketfeed.Ticker)]

data.subscribe_symbols(sub_instruments)

# Unsubscribe instruments which are already active on connection
unsub_instruments = 
    [(marketfeed.NSE, "1333", 16)]

data.unsubscribe_symbols(unsub_instruments)
```

### Live Order Update Usage
```python
from dhanhq import orderupdate
import time

# Add your Dhan Client ID and Access Token
client_id = "Dhan Client ID"
access_token = "Access Token"

def run_order_update():
    order_client = orderupdate.OrderSocket(client_id, access_token)
    while True:
        try:
            order_client.connect_to_dhan_websocket_sync()
        except Exception as e:
            print(f"Error connecting to Dhan WebSocket: {e}. Reconnecting in 5 seconds...")
            time.sleep(5)

run_order_update()
```

## Changelog

[Check release notes](https://github.com/dhan-oss/DhanHQ-py/releases)

            

Raw data

            {
    "_id": null,
    "home_page": "https://dhanhq.co/",
    "name": "dhanhq",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "Dhan",
    "author_email": "dhan-oss@dhan.co",
    "download_url": "https://files.pythonhosted.org/packages/16/b2/e284f299f95190cba6cac6173b8147ad4e25ffaac6000a2001c4b3a77dd8/dhanhq-2.0.1.tar.gz",
    "platform": null,
    "description": "# DhanHQ-py : v2.0.0\n\n[![PyPI](https://img.shields.io/pypi/v/dhanhq.svg)](https://pypi.org/project/dhanhq/)\n\n\nThe official Python client for communicating with the [Dhan API](https://api.dhan.co/v2/)  \n\nDhanHQ-py Rest API is used to automate investing and trading. Execute orders in real time along with position management, live and historical data, tradebook and more with simple API collection.\n\nNot just this, you also get real-time market data via DhanHQ Live Market Feed.\n\n\n[Dhan](https://dhan.co) (c) 2024. Licensed under the [MIT License](https://github.com/dhan-oss/DhanHQ-py/blob/main/LICENSE)\n\n### Documentation\n\n- [DhanHQ Developer Kit](https://api.dhan.co/v2/)\n- [DhanHQ API Documentation](https://dhanhq.co/docs/v2/)\n\n\n## v2.0 - What's New\n\nDhanHQ v2 extends execution capability with live order updates, market quotes and forever orders on superfast APIs. Some of the key highlights from this version are:\n    \n- Fetch LTP, Quote (with OI) and Market Depth data directly on API, for upto 1000 instruments at once with Market Quote API.\n\n- Option Chain API which gives OI, greeks, volume, top bid/ask and price data of all strikes of a particular underlying.\n\n- Place, modify and manage your Forever Orders, including single and OCO orders to manage risk and trade efficiently with Forever Order API.\n\n- Order Updates are sent in real time via websockets, which will update order status of all your orders placed via any platform - `order_update`.\n\n- Intraday Minute Data now provides OHLC with Volume data for last 5 trading days across timeframes such as 1 min, 5 min, 15 min, 25 min and 60 min - `intraday_minute_data`.\n\n- Full Packet in Live Market Feed (`marketfeed`).\n\n- Margin Calculator (`margin_calculator`) and Kill Switch (`kill_switch`) APIs.\n\n### Breaking Changes\n\n- Replaced `intraday_daily_minute_data` and `historical_minute_charts` as functions from v1.2.4\n\n- `quantity` field needs to be placed order quantity instead of pending order quantity in Order Modification\n\n- EPOCH time instead of Julian time in Historical Data API, and same changed for `convert_to_date_time` function\n\n- `historical_daily_data` takes `security_id` as argument instead of `symbol`\n\n- Nomenclature changes in `get_order_by_corelationID` to `get_order_by_correlationID`.\n\nYou can read about all other updates from DhanHQ V2 here: [DhanHQ Releases](https://dhanhq.co/docs/v2/releases/).\n\n\n## Features\n\n* **Order Management**  \nThe order management APIs lets you place a new order, cancel or modify the pending order, retrieve the order status, trade status, order book & tradebook.\n\n* **Live Market Feed**  \nGet real-time market data to power your trading systems, with easy to implement functions and data across exchanges.\n\n* **Market Quote**  \nREST APIs based market quotes which given you snapshot of ticker mode, quote mode or full mode.\n\n* **Option Chain**  \nSingle function which gives entire Option Chain across exchanges and segments, giving OI, greeks, volume, top bid/ask and price data.\n\n* **Forever Order**  \nPlace, modify or delete Forever Orders, whether single or OCO to better manage your swing trades.\n\n* **Portfolio Management**  \nWith this set of APIs, retrieve your holdings and positions in your portfolio as well as manage them.\n\n* **Historical Data**  \nGet historical candle data for the desired scrip across segments & exchange, both multiple minute timeframe OHLC and Daily OHLC.\n\n* **Fund Details**  \nGet all information of your trading account like balance, margin utilised, collateral, etc as well margin required for any order.\n\n* **eDIS Authorisation**  \nTo sell holding stocks, one needs to complete the CDSL eDIS flow, generate T-PIN & mark stock to complete the sell action.\n\n## Quickstart\n\nYou can install the package via pip\n\n```\npip install dhanhq\n```\n\n\n\n### Hands-on API\n\n```python\nfrom dhanhq import dhanhq\n\ndhan = dhanhq(\"client_id\",\"access_token\")\n\n# Place an order for Equity Cash\ndhan.place_order(security_id='1333',            # HDFC Bank\n    exchange_segment=dhan.NSE,\n    transaction_type=dhan.BUY,\n    quantity=10,\n    order_type=dhan.MARKET,\n    product_type=dhan.INTRA,\n    price=0)\n    \n# Place an order for NSE Futures & Options\ndhan.place_order(security_id='52175',           # Nifty PE\n    exchange_segment=dhan.NSE_FNO,\n    transaction_type=dhan.BUY,\n    quantity=550,\n    order_type=dhan.MARKET,\n    product_type=dhan.INTRA,\n    price=0)\n  \n# Fetch all orders\ndhan.get_order_list()\n\n# Get order by id\ndhan.get_order_by_id(order_id)\n\n# Modify order\ndhan.modify_order(order_id, order_type, leg_name, quantity, price, trigger_price, disclosed_quantity, validity)\n\n# Cancel order\ndhan.cancel_order(order_id)\n\n# Get order by correlation id\ndhan.get_order_by_corelationID(corelationID)\n\n# Get Instrument List\ndhan.fetch_security_list(\"compact\")\n\n# Get positions\ndhan.get_positions()\n\n# Get holdings\ndhan.get_holdings()\n\n# Intraday Minute Data\ndhan.intraday_minute_data(security_id,exchange_segment,instrument_type)\n\n# Historical Daily Data\ndhan.historical_daily_data(security_id,exchange_segment,instrument_type,expiry_code,from_date,to_date)\n\n# Time Converter\ndhan.convert_to_date_time(EPOCH Date)\n\n# Get trade book\ndhan.get_trade_book(order_id)\n\n# Get trade history\ndhan.get_trade_history(from_date,to_date,page_number=0)\n\n# Get fund limits\ndhan.get_fund_limits()\n\n# Generate TPIN\ndhan.generate_tpin()\n\n# Enter TPIN in Form\ndhan.open_browser_for_tpin(isin='INE00IN01015',\n    qty=1,\n    exchange='NSE')\n\n# EDIS Status and Inquiry\ndhan.edis_inquiry()\n\n# Expiry List of Underlying\ndhan.expiry_list(\n    under_security_id=13,                       # Nifty\n    under_exchange_segment=\"IDX_I\"\n)\n\n# Option Chain\ndhan.option_chain(\n    under_security_id=13,                       # Nifty\n    under_exchange_segment=\"IDX_I\",\n    expiry=\"2024-10-31\"\n)\n\n# Market Quote Data                     # LTP - ticker_data, OHLC - ohlc_data, Full Packet - quote_data\ndhan.ohlc_data(\n    securities = {\"NSE_EQ\":[1333]}\n)\n\n# Place Forever Order (SINGLE)\ndhan.place_forever(\n    security_id=\"1333\",\n    exchange_segment= dhan.NSE,\n    transaction_type= dhan.BUY,\n    product_type=dhan.CNC,\n    product_type= dhan.LIMIT,\n    quantity= 10,\n    price= 1900,\n    trigger_Price= 1950\n)\n```\n\n### Market Feed Usage\n```python\nfrom dhanhq import marketfeed\n\n# Add your Dhan Client ID and Access Token\nclient_id = \"Dhan Client ID\"\naccess_token = \"Access Token\"\n\n# Structure for subscribing is (exchange_segment, \"security_id\", subscription_type)\n\ninstruments = \n    [(marketfeed.NSE, \"1333\", marketfeed.Ticker),   # Ticker - Ticker Data\n    (marketfeed.NSE, \"1333\", marketfeed.Quote),     # Quote - Quote Data\n    (marketfeed.NSE, \"1333\", marketfeed.Full),      # Full - Full Packet\n    (marketfeed.NSE, \"11915\", marketfeed.Ticker),\n    (marketfeed.NSE, \"11915\", marketfeed.Full)]\n\nversion = \"v2\"          # Mention Version and set to latest version 'v2'\n\n# In case subscription_type is left as blank, by default Ticker mode will be subscribed.\n\ntry:\n    data = marketfeed.DhanFeed(client_id, access_token, instruments, version)\n    while True:\n        data.run_forever()\n        response = data.get_data()\n        print(response)\n\nexcept Exception as e:\n    print(e)\n\n# Close Connection\ndata.disconnect()\n\n# Subscribe instruments while connection is open\nsub_instruments = \n    [(marketfeed.NSE, \"14436\", marketfeed.Ticker)]\n\ndata.subscribe_symbols(sub_instruments)\n\n# Unsubscribe instruments which are already active on connection\nunsub_instruments = \n    [(marketfeed.NSE, \"1333\", 16)]\n\ndata.unsubscribe_symbols(unsub_instruments)\n```\n\n### Live Order Update Usage\n```python\nfrom dhanhq import orderupdate\nimport time\n\n# Add your Dhan Client ID and Access Token\nclient_id = \"Dhan Client ID\"\naccess_token = \"Access Token\"\n\ndef run_order_update():\n    order_client = orderupdate.OrderSocket(client_id, access_token)\n    while True:\n        try:\n            order_client.connect_to_dhan_websocket_sync()\n        except Exception as e:\n            print(f\"Error connecting to Dhan WebSocket: {e}. Reconnecting in 5 seconds...\")\n            time.sleep(5)\n\nrun_order_update()\n```\n\n## Changelog\n\n[Check release notes](https://github.com/dhan-oss/DhanHQ-py/releases)\n",
    "bugtrack_url": null,
    "license": "MIT LICENSE",
    "summary": "The official Python client for communicating with the DhanHQ API",
    "version": "2.0.1",
    "project_urls": {
        "Homepage": "https://dhanhq.co/"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d1c0432d30efd4e3f20751f85844e9cf276c008664943a843cc94b8d885c51e3",
                "md5": "b24c387396191089b260e545618e90b8",
                "sha256": "be42f9a824e34876935822e485df46b6385e344b01b8f188409e9283ae547d89"
            },
            "downloads": -1,
            "filename": "dhanhq-2.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b24c387396191089b260e545618e90b8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 18196,
            "upload_time": "2024-11-07T06:26:35",
            "upload_time_iso_8601": "2024-11-07T06:26:35.594410Z",
            "url": "https://files.pythonhosted.org/packages/d1/c0/432d30efd4e3f20751f85844e9cf276c008664943a843cc94b8d885c51e3/dhanhq-2.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "16b2e284f299f95190cba6cac6173b8147ad4e25ffaac6000a2001c4b3a77dd8",
                "md5": "0720c3e4ef6b4aa7758715496e050010",
                "sha256": "c119b2d9234c31e7a4187205611400a9b96eb6c1d673b115f4ed3be5a3d69c80"
            },
            "downloads": -1,
            "filename": "dhanhq-2.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "0720c3e4ef6b4aa7758715496e050010",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 21346,
            "upload_time": "2024-11-07T06:26:36",
            "upload_time_iso_8601": "2024-11-07T06:26:36.906751Z",
            "url": "https://files.pythonhosted.org/packages/16/b2/e284f299f95190cba6cac6173b8147ad4e25ffaac6000a2001c4b3a77dd8/dhanhq-2.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-07 06:26:36",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "dhanhq"
}
        
Elapsed time: 0.41040s