Generate Dhan Token Automatically with Python

Looking for a simple way to generate your Dhan token using Python?

You don’t need bots, Streamlit, Selenium, or any scraping hacks—just import the token module and generate the token directly.

:pushpin: Sample code: tinyurl.com/dhan-token
:movie_camera: Quick demo: YouTube - Token Generation Walkthrough

It’s lightweight, straightforward, and easy to integrate into your workflow.

@Hardik Thanks :pray: for Dhan Api V2.0 auth mechanism

2 Likes

why are you sharing an encrypted file ? share the source code

@Kush

Good question, but I think the DHAN team is the right person to explain why they have encrypted the payload passed to the backend during API calls (as shown in the image below).

I don’t have the right to disclose DHAN’s encryption/decryption logic.

But if your concern is about data security, there’s nothing to worry about. Still, if you want to verify, you can trace all data transfers from/to tool using Wireshark or similar TCPDump tools.

If you don’t want to rely on third-party library, you can also automate the process with a Python script, though it will take some effort.

Also, the video I shared was only to demonstrate possibilities, nothing more is possible beyond that.

1 Like

no issue . thanks for showing the proof
the workaround you have coded is selenium based or you have reverse engineered apis @Titamazon

I don’t have the right to disclose DHAN’s encryption/decryption logic.

its all right there in the browser code tho :stuck_out_tongue:

Can we trust the sample code especially the pye file, is it from dhan or personal made file?

no, sharing creds literally means you are handling over the full access of your account.,

Reverse engineering something is totally valid, idk what is his problem with sharing the code. Dont share if you dont want to, share if you do,

But not posting source code of something that involves user’s money is dumb af

i am getting the below error for code,which i was not getting earlier, the dhan_token_automate.pye file is in the folder itself, its not detecting

Exception has occurred: ImportError

exception: no description

File “C:\Users\simri\Desktop\bot\After SEBI Main Bot - multi accnt\2.Access_token_generator.py”, line 7, in

from dhan_token_automate import GetAccessToken

ImportError:

@Ashutosh_Raina Read here.

from dhanhq import DhanLogin
ImportError: cannot import name ‘DhanLogin’ from ‘dhanhq’

Install the package.

Can I configure a DHCP reservation (private static IP) from my router (e.g., 192.168.1.1) for my setup? I’m running a Python script that places around 1–4 orders per day. Will this work to ensure stable connectivity and avoid any IP-related issues for my script?

@Ashutosh_Raina No.

In any of you are into AWS, the below mentioned script is more helpful.

import json
import boto3
import os
from datetime import datetime
import logging
import requests
import pyotp

logger = logging.getLogger()
logger.setLevel(logging.INFO)

s3_client = boto3.client("s3")

# Configuration
S3_BUCKET = os.environ.get("S3_BUCKET", "???")
S3_KEY = "Dhan/AccessToken/access_token.txt"
DHAN_AUTH_URL = "https://auth.dhan.co/app/generateAccessToken"

# Secrets from environment variables
DHAN_CLIENT_ID = os.environ.get("DHAN_CLIENT_ID")
DHAN_PIN = os.environ.get("DHAN_PIN")
DHAN_TOTP_SECRET = os.environ.get("DHAN_TOTP_SECRET")

def generate_totp():
    """Generate current TOTP token"""
    if not DHAN_TOTP_SECRET:
        raise ValueError("DHAN_TOTP_SECRET not configured")
    totp = pyotp.TOTP(DHAN_TOTP_SECRET)
    return totp.now()


def get_dhan_access_token():
    """Authenticate with Dhan and retrieve access token"""
    if not all([DHAN_CLIENT_ID, DHAN_PIN, DHAN_TOTP_SECRET]):
        raise ValueError("Missing required Dhan credentials in environment")

    totp = generate_totp()
    logger.info(f"Generated TOTP for client {DHAN_CLIENT_ID}")

    try:
        response = requests.post(
            DHAN_AUTH_URL,
            data={
                "dhanClientId": DHAN_CLIENT_ID,
                "pin": DHAN_PIN,
                "totp": totp
            },
            timeout=10
        )
        response.raise_for_status()

        data = response.json()
        if "accessToken" not in data:
            logger.error(f"No accessToken in response: {data}")
            raise ValueError("Access token not found in Dhan response")

        return data["accessToken"]

    except requests.exceptions.RequestException as e:
        logger.error(f"Dhan authentication failed: {str(e)}")
        raise


def upload_to_s3(access_token):
    """Upload access token to S3"""
    try:
        metadata = {
            "generated_at": datetime.utcnow().isoformat(),
            "client_id": DHAN_CLIENT_ID
        }

        s3_client.put_object(
            Bucket=S3_BUCKET,
            Key=S3_KEY,
            Body=access_token.encode("utf-8"),
            Metadata=metadata,
            ServerSideEncryption="AES256"
        )
        logger.info(f"Uploaded access token to s3://{S3_BUCKET}/{S3_KEY}")
        return True

    except Exception as e:
        logger.error(f"S3 upload failed: {str(e)}")
        raise


def lambda_handler(event, context):
    """
    Lambda handler for Dhan access token generation and S3 storage.

    Returns:
        dict: Lambda response with status and token info
    """
    try:
        logger.info("Starting Dhan access token generation")

        # Get access token from Dhan
        access_token = get_dhan_access_token()
        logger.info(f"Successfully retrieved access token (length: {len(access_token)})")

        # Upload to S3
        upload_to_s3(access_token)

        return {
            "statusCode": 200,
            "body": json.dumps({
                "message": "Access token generated and stored successfully",
                "s3_location": f"s3://{S3_BUCKET}/{S3_KEY}",
                "timestamp": datetime.utcnow().isoformat()
            })
        }

    except ValueError as e:
        logger.error(f"Configuration error: {str(e)}")
        return {
            "statusCode": 400,
            "body": json.dumps({"error": f"Configuration error: {str(e)}"})
        }

    except Exception as e:
        logger.error(f"Unexpected error: {str(e)}", exc_info=True)
        return {
            "statusCode": 500,
            "body": json.dumps({"error": f"Internal error: {str(e)}"})
        }

Lamda can’t be used for order placements so a VPS can handle login and order placement.

You can just trigger this lambda to generate a token and save it in s3. Your VPS can then fetch it from S3 to be used throughout the day.

Isn’t this would make more sense if lamda could provide static IP but as of now they don’t. Any benefit of using S3 when a user can save this in the DB on the VPS?

Any benefit of using S3 when a user can save this in the DB on the VPS?

One benefit I can think of is that it can be easily queried from outside of AWS for local testing.

But if your architecture is more simpler by storing it on VPS you can go ahead with that.

My approach is too keep all the moving parts as independent as possible. So, any computation not required on EC2 should not take place there.

Also, I am using S3 extensively for storing daily security master, binary data, etc., so it makes sense for me to also use it for storing token.