DhanHQ Python SDK

repository·main·Indexed 41 days ago

https://github.com/dhan-oss/dhanhq-py

The official Python SDK for the Dhan API, enabling developers to automate trading, manage portfolios, and access real-time market data for Indian and US (Global) stocks. Key features include order management, WebSocket live market feeds, option chain retrieval, conditional orders, and historical OHLC candle data.

Tokens
12.9K
Snippets
58
Records
68
Agent score
52%

What's inside DhanHQ

  1. Overview of DhanHQ-py features

    main

    DhanHQ-py is the official Python client for the Dhan API, designed to automate investing and trading. Key capabilities include:

    • Order Management: Place, cancel, or modify orders; retrieve order/trade status, order book, and tradebook.
    • Live Market Feed: Real-time market data via WebSocket.
    • Market Quote: REST API snapshots in ticker, quote, or full mode.
    • Option Chain: Retrieve entire option chains including OI, greeks, volume, and bid/ask data.
    • Forever Orders: Manage single or OCO (One-Cancels-the-Other) swing trades.
    • Conditional Orders: Automate orders based on price or technical-indicator conditions (Equities & Indices).
    • Global Stocks: Trade US stocks, including orders, holdings, fund limits, and market status, with a dedicated live feed.
    • P&L based Exit: Automatically square-off positions when cumulative profit or loss hits specific thresholds.
    • Multi-leg Margin Calculator: Compute combined margin for multiple orders with hedge benefits.
    • Portfolio Management: Retrieve and manage holdings and positions.
    • Historical Data: Fetch OHLC candle data (multiple minute timeframes and Daily) for various scrips.
    • Fund Details: Access account balance, margin utilized, collateral, and margin requirements.
    • eDIS Authorisation: Manage CDSL eDIS flows, including T-PIN generation and marking stocks for sale.
  2. Initialize the Dhan client

    main

    To interact with trading APIs, first create a DhanContext with your client_id and access_token, then pass it to the dhanhq constructor to get a client instance.

    from dhanhq import DhanContext, dhanhq
    
    dhan_context = DhanContext("client_id","access_token")
    dhan = dhanhq(dhan_context)
  3. Configure credentials for integration tests

    main

    Integration tests require valid credentials to run. You must create a .env file from the provided sample:

    1. Rename test.env.sample to test.env.
    2. Add your client-id and access-token to the test.env file.
  4. Run unit, integration, and all tests

    main

    The project provides several ways to run tests. You can use the provided helper scripts or run pytest directly.

    Using Helper Scripts

    • pytu: Runs unit tests.
    • pyti: Runs integration tests.
    • pyt: Runs both unit and integration tests.

    Note: If the scripts fail to run, ensure they have execution permissions using chmod u+x init-dev-env.sh.

    Using pytest directly

    • Unit Tests: pytest tests/unit --cache-clear -s
    • Integration Tests: pytest tests/integration --cache-clear -s
    • All Tests: pytest --cache-clear -s

    To avoid issues with stale test data, it is recommended to use the --cache-clear flag.

    # Run specific test file
    pytest ./tests/test_dhanhq.py --cache-clear -v
    
    # Run a specific test group within a file
    pytest ./tests/test_dhanhq.py::TestDhanhq_GetOrderList --cache-clear -v
  5. Install the DhanHQ-py pre-release version

    main

    The v2.3.0rc1 version is a release candidate for testing new features like Conditional Orders and Global Stocks. It is not the latest stable release, so a standard pip install dhanhq will not install it. To use the pre-release, you must install it explicitly using the --pre flag.

    pip install --pre dhanhq==2.3.0rc1
  6. Contribute to the project

    main

    To contribute to dhanhq-py, follow this workflow:

    1. Fork the repository to your GitHub account.
    2. Clone your fork locally.
    3. Setup your local environment using the development setup guide.
    4. Branch: Create a new local branch (e.g., git checkout -n new_feature).
    5. Develop: Implement your changes and commit them locally.
    6. Push: Push your branch to your remote fork.
    7. Merge Request: Submit a merge request to the main Dhanhq repository.
    8. Sync: Once merged, sync your fork's main branch with the upstream repository.
  7. Authenticate using OAuth Flow

    main

    Use the DhanLogin class to implement an OAuth flow. This involves two steps: generating a login session to get a consent ID (which opens a browser for the user to log in), and then consuming the token_id received from the redirect URL to obtain the final access_token.

    from dhanhq import DhanLogin
    
    dhan_login = DhanLogin("YOUR_CLIENT_ID")
    app_id = "YOUR_APP_ID"
    app_secret = "YOUR_APP_SECRET"
    
    # Step 1: Generate Consent and Open Browser for Login
    consent_id = dhan_login.generate_login_session(app_id, app_secret)
    
    # Step 2: Consume Token ID (After user logs in and gets Token ID from redirect URL)
    token_id = "TOKEN_ID_FROM_REDIRECT_URL"
    access_token = dhan_login.consume_token_id(token_id, app_id, app_secret)
    print(access_token)
  8. Set up the local development environment

    main

    To prepare your local environment for contributing to dhanhq-py, follow these steps to manage Python versions and virtual environments:

    1. Manage Python Version: Use pyenv to ensure you are using the correct Python version (e.g., 3.9.2).
    2. Create Virtual Environment: Use python3 -m venv .venv to create an isolated environment.
    3. Activate Environment: Run source .venv/bin/activate to enter the environment.
    4. Install Project in Editable Mode: Install the package along with development dependencies using pip install -e '.[dev]'.

    Note: If you modify setup.py, you must re-run the editable installation command to apply changes.

    # Example workflow using pyenv and venv
    pyenv local 3.9.2
    python3 -m venv .venv
    source .venv/bin/activate
    pip install -e '.[dev]'
  9. Authenticate using PIN & TOTP Flow

    main

    For a direct authentication method, use DhanLogin.generate_token by providing the user's PIN and TOTP.

    from dhanhq import DhanLogin
    
    dhan_login = DhanLogin("YOUR_CLIENT_ID")
    pin = "YOUR_PIN"
    totp = "YOUR_TOTP"
    
    access_token_data = dhan_login.generate_token(pin, totp)
    print(access_token_data)
  10. Understand GlobalStocksFeed data packet types

    main

    The GlobalStocksFeed parses binary packets into several distinct dictionary types based on the msg_code.

    Supported Packet Types

    TypeMsgCodeDescription
    Trade1Real-time trade data including LTP, LTQ, volume, ATP, OI, LTT (time), and LUT (time).
    OHLC3Open, High, Low, and Close prices.
    Market Status29Current market type and status.
    Previous Close32Previous close price and Open Interest.
    Circuit Limit33Upper and lower circuit limits.
    52 Week High Low3652-week high and low prices.
    Error50Error notifications (e.g., connection limits, expired tokens).

    Error Codes

    If an Error packet is received, the error_code maps to:

    • 805: Connection limit exceeded.
    • 806: Payment not done for broadcast.
    • 807: Token expired.
    • 808: Authentication failure.
    • 809: Invalid token.
  11. Understand MarketFeed data packet types

    main

    The on_message (or on_ticks) callback receives a dictionary representing the parsed market data. The type field in the dictionary identifies the data format:

    • Ticker Data: Contains LTP (Last Traded Price) and LTT (Last Traded Time).
    • Market Depth: Contains LTP and a depth list of 5 levels (bid/ask quantity, orders, and prices).
    • Quote Data: Comprehensive data including LTP, LTQ (Last Traded Quantity), avg_price, volume, open, high, low, close, and total buy/sell quantities.
    • OI Data: Contains Open Interest (OI) information.
    • Previous Close: Contains prev_close and prev_OI.
    • Full Data: A combination of Quote Data, OI, and Market Depth.
    • Market Status: Returns a string (e.g., "Markets Open").