shreyash-Pandey-Katni/Dhan-MCP-Server
If you are the rightful owner of Dhan-MCP-Server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
CopilotBasedTrading is a Model Context Protocol (MCP) Server designed for seamless integration with DhanHQ's trading APIs, providing secure and real-time access to Indian stock market data, portfolio management, and options trading.
🚀 CopilotBasedTrading - DhanHQ MCP Server
A comprehensive Model Context Protocol (MCP) Server for seamless integration with DhanHQ's trading APIs. This project provides secure, real-time access to Indian stock market data, portfolio management, and options trading through GitHub Copilot and other MCP-compatible AI assistants.
✨ Features
📊 Market Data & Analytics
- Real-time OHLC data - Live market quotes and price movements
- Historical data retrieval - Daily and intraday price history
- Instrument lookup - Search and discover securities across NSE/BSE
- Market depth analysis - Bid/ask spreads and volume data
📈 Options Trading Suite
- Options chain data - Complete option chains with Greeks (Delta, Theta, Gamma, Vega)
- Expiry date lookup - Available expiry dates for any underlying
- Strike price analysis - Real-time option prices and implied volatility
- Options discovery - Find specific option contracts by filters
💼 Portfolio Management
- Holdings tracking - View current equity positions
- P&L monitoring - Real-time profit/loss calculations
- Order management - Place, modify, and cancel orders
- Position analysis - Detailed position breakdowns
🔒 Security & Reliability
- Zero fake data - All responses use real DhanHQ APIs
- Secure credential handling - Multiple configuration methods
- Rate limiting compliance - Respects API limits (1 req/3sec for options)
- Comprehensive error handling - Graceful failure management
🛠️ Installation
Prerequisites
- Python 3.8+
- DhanHQ Account with API access
- Valid API credentials (Client ID + Access Token)
Quick Setup
# Clone the repository
git clone <repository-url>
cd CopilotBasedTrading
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install --upgrade pip
pip install -r requirements.txt
🔐 Configuration
Method 1: Environment Variables (Recommended)
export DHAN_CLIENT_ID="your_client_id_here"
export DHAN_ACCESS_TOKEN="your_access_token_here"
Method 2: Configuration File
Create config.ini in the project root:
[dhan]
client_id = your_client_id_here
access_token = your_access_token_here
mode = live
Method 3: Development/Testing Mode
export DHAN_FAKE=1 # Uses sandbox mode with mock data
🚀 Usage
Running the MCP Server
# Activate virtual environment
source .venv/bin/activate
# Start the MCP server
python -m mcp_dhan_server.server
Integration with GitHub Copilot
Add to your MCP configuration (typically ~/.config/mcp/mcp.json):
{
"servers": {
"dhan-trading": {
"command": "python",
"args": ["-m", "mcp_dhan_server.server"],
"cwd": "/path/to/CopilotBasedTrading",
"env": {
"DHAN_CLIENT_ID": "your_client_id",
"DHAN_ACCESS_TOKEN": "your_access_token"
}
}
}
}
📋 Available Tools
📈 Market Data Tools
| Tool | Description | Example |
|---|---|---|
get_holdings | Fetch current equity holdings | Portfolio analysis |
get_positions | Retrieve active trading positions | P&L tracking |
get_orders | View order book history | Order management |
ohlc_data | Real-time OHLC quotes | Live price monitoring |
intraday_minute_data | Minute-level price data | Technical analysis |
historical_daily_data | Historical OHLC data | Backtesting |
🎯 Options Trading Tools
| Tool | Description | Example |
|---|---|---|
get_option_chain | Complete option chain with Greeks | Options strategy analysis |
get_option_expiry_list | Available expiry dates | Expiry planning |
lookup_options | Find specific option contracts | Contract discovery |
🔍 Discovery Tools
| Tool | Description | Example |
|---|---|---|
lookup_security_id | Search for instruments by name/symbol | Security research |
📝 Trading Tools
| Tool | Description | Example |
|---|---|---|
place_order | Execute buy/sell orders | Trade execution |
cancel_order | Cancel pending orders | Order management |
📊 Example Queries
Portfolio Analysis
"Show me my current holdings and their P&L"
Options Strategy Research
"Get the option chain for NIFTY 50 expiring on 2025-09-16 and find the best call options around 25000 strike"
Market Analysis
"Fetch the last 30 days of historical data for RELIANCE and analyze the price trend"
Live Trading
"Get real-time OHLC data for the top 5 NSE stocks and identify any trading opportunities"
🏗️ Architecture
CopilotBasedTrading/
├── mcp_dhan_server/ # Core MCP server implementation
│ ├── server.py # Main server with all trading tools
│ └── config.py # Configuration management
├── scripts/ # Utility scripts
│ ├── fetch_market_data.py # Market data collection
│ └── analyze_and_report.py # Analysis and reporting
├── requirements.txt # Python dependencies
├── config.ini.example # Sample configuration
└── README.md # This file
🔧 Development
Running Tests
# Run with fake/mock data
DHAN_FAKE=1 python -m mcp_dhan_server.server
Debugging
# Enable detailed logging
export DHAN_LOG_LEVEL=DEBUG
python -m mcp_dhan_server.server
⚠️ Important Notes
Security
- Never commit
config.inior files containing API credentials - Use environment variables in production
- Regularly rotate API tokens
- Monitor API usage and costs
Trading Risks
- Real Money: This system places actual trades in live markets
- Test thoroughly in sandbox mode before live trading
- Implement proper risk management and position sizing
- Monitor market conditions and system performance
API Limits
- Options data: 1 request per 3 seconds
- Other endpoints: Follow DhanHQ's rate limiting guidelines
- Implement proper retry mechanisms for production use
🤝 Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the file for details.
🆘 Support
- Issues: Open a GitHub issue for bugs or feature requests
- Documentation: Refer to DhanHQ API Documentation
- Community: Join trading and MCP development communities
🙏 Acknowledgments
- DhanHQ for providing comprehensive trading APIs
- Anthropic for the Model Context Protocol specification
- GitHub Copilot for AI-powered development assistance
- Indian Trading Community for feedback and testing
⚠️ Disclaimer: This software is for educational and research purposes. Trading in financial markets involves substantial risk. The authors are not responsible for any financial losses incurred through the use of this software. Always conduct your own research and consider consulting with financial advisors before making investment decisions.
🔥 Happy Trading! 📈