Connecting Dhan to Gemini or ChatGPT?

I’m really impressed with how much Gemini is helping me analyze my trades. The insights it gives me into my trading patterns, behavioral biases, and overall performance infographics are incredibly valuable—honestly, no trade journal in the World even comes close.

The only snag is that I have to manually type in every single trade, along with the timestamp, commissions, and other details, into an Excel file so Gemini can understand it. It’s quite a bit of work.

I was wondering if there’s a way to automate this by connecting my Dhan account directly to Gemini or even ChatGPT to pull all my historical trade data automatically?

2 Likes

@thisisbanerjee I am glad you asked this question. I am trying to build something similar by calling the https://api.dhan.co/v2/orders and https://api.dhan.co/v2/trades. The problem is that unless these trades are routed through a VectorStore and then given to the model, the querying won’t work. The other option is to route it via the Model Context Protocol, which is a research topic, but ChatGPT and Gemini UI do not give options to link it directly.

The only way I can see is to write a program to massage the data from the APIs and convert it to an Excel sheet or CSV file. Then give that file to ChatGPT or Gemini, which reduces the manual effort of manually typing in every single trade.

FYI: the APIs will only give the day’s trades and orders, and hence necessary to store them in a database so that the history is built.

1 Like

Hi @thisisbanerjee,

While we don’t officially support a way of automating this currently, I’m curious to understand if we can make this easier with any current report that we have on Journal?

@Anirudha, in my opinion, the changes in the following section should help without the need of a program to massage the data from the api.
1: Past Trades = Add a download option and a selection for Segments. The download template should be simple, with a table with Header and Data and add the timestamp DD-MM-YYYY HH:MM:SS in the section for each row i.e. Buy and Sell.

Also, while researching I found a brokerage who’s supporting MCP integration to AI.

I don’t know whether I should be happy or sad.

2 Likes

The current reports are fine, only the addition of timestamp would suffice.

It would make me very sad :smiley: .

1 Like

Just want to update the community if someone else hasn’t already done it, we can create a local MCP server and link it to claude. Pre-requisites are python & pip, and of course claude

Steps
1: pip install uv
2: uv init dhanmcp
3: cd dharmcp
4: uv venv
5: source .venv/bin/activate
6: uv add “mcp[cli]” httpx
7: uv pip install fastapi httpx fastmcp python-dotenv uvicorn
8: Copy the following in main.py

import httpx
from mcp.server.fastmcp import FastMCP

# Define your MCP server
mcp = FastMCP("Dhan Trade Analyzer")

# Constants
DHAN_API_URL = "https://api.dhan.co/trades"
ACCESS_TOKEN = "<your access token here>"

@mcp.tool()
async def get_today_trades(format: str = "text") -> str:
    """
    Fetch today's trades from Dhan and return them as a summary (text) or raw data (JSON).
    """
    headers = {
        "access-token": ACCESS_TOKEN,
        "Content-Type": "application/json"
    }

    async with httpx.AsyncClient() as client:
        response = await client.get(DHAN_API_URL, headers=headers)
    
    if response.status_code != 200:
        return f"Error: Failed to fetch trades. Status code: {response.status_code}. Details: {response.text}"

    trades = response.json()

    processed = [
        {
            "symbol": t["tradingSymbol"],
            "type": t["transactionType"],
            "quantity": t["tradedQuantity"],
            "time": t["exchangeTime"],
            "price": t["tradedPrice"]
        }
        for t in trades
    ]

    if format == "json":
        return str(processed)

    # Text summary
    summary = "\n".join([
        f"{i+1}. {t['type']} {t['symbol']}, quantity: {t['quantity']}, price: ₹{t['price']}, time: {t['time']}"
        for i, t in enumerate(processed)
    ])
    return summary

# Run the MCP server
if __name__ == "__main__":
    mcp.run()

9: Open Claude → Settings → Developer
10: Edit Config and add the following

{
    "mcpServers": {
        "dhanmcp": {
            "command": "<Absolute path to uv installed in point 1>",
            "args": [
                "--directory",
                "Absolute path to dhanmcp created in point 2",
                "run",
                "main.py"
            ]
        }
    }
}

11: Restart claude and use the chat. Currently, the file only has one method, “get_today_trades,” but it can be extended to have more methods, and the response can be formatted accordingly.

The primary source referred to during creation of the above steps is here.

2 Likes

Appreciate your efforts put in @nitishbangera :smiley: Will give it a spin this weekend.

1 Like

@thisisbanerjee Thanks. Great to know that you will take it for a spin. Please replace the API with the V2 version mentioned here .

1 Like

can you share a video or give some insight as to how to use it

@kanhaji Follow the steps mentioned, and you should be set using this local mcp server. Create the access token from the dropdown on your Photo in web.dhan.co(Top right) → Access dhanHQ Apis → Trading Apis. For Apis, check the Dhan Documentation here.

Ahh just closed there account ( zerodha ) for dhan :face_in_clouds:

@Abhijeet_Rajgor Why did you close Dhan account? :smiling_face_with_tear:

people overreact i guess… i mean why would i like to share my trading data with an AI i mean i want to gain insights but still don’t i have lot of data already shared with AI? maybe i they can be utilized by these companies to cross-sell products

yahi hai jo kuch din phele bol rahe the ki Dhan kuch jayada permission and data collect karta hai. woh apni marzi se AI par sara data share kar rahe hai ab
@thisisbanerjee @PravinJ

@aditya34608 @onkar You are probably right, but this is just one instance where you can leverage AI. If cloud-deployed models and clients are a problem, then you can self-host using ollama and gain insights. Also, a lot of these people who want to leverage information would do it via order books as well. The bottom line is that the potential of getting data is endless in today’s world, and AI is just one source.

Actually, I was thinking about those people who have multiple social apps installed on their phones and make comments on user data and privacy after reading a random post by someone on a social platform about how the broking apps collect data and concerns about their usage.

no sry lzy typing closed zerodha ( when now they are pushing all updates dhan already has)

1 Like

At the end of the day, it really comes down to individual comfort. Having been part of Dhan’s journey from the early days—watching it go from 0 to 1—I’ve grown pretty comfortable with the platform.

They’ve always come across as genuinely good folks, and I personally feel more at ease with Dhan than with Z or any other brokerage. They’ve been transparent about user privacy too—no personal tracking, as @PravinJ reaffirmed just a few days ago.

Like I said, comfort is subjective. Some people connect with a platform, stick around, share both praise and criticism to help it grow. Others might just not vibe with it and will tear it down—sometimes without solid reasoning.