π Advanced Algorithmic Trading System for MCX Gold Futures & Options
Powered by DhanHQ API v2.1.0 | Real-time Data | Automated Trading | Risk Management
- π― Overview
- β¨ Key Features
- π Supported Instruments
- π οΈ Installation
- π§ Configuration
- π Project Structure
- π Quick Start Guide
- π Trading Strategies
- π Usage Examples
- π Market Data Types
- β‘ Advanced Features
- π‘οΈ Risk Management
- π± Monitoring & Alerts
- π§ Troubleshooting
- π API Documentation
- π€ Contributing
β οΈ Disclaimer- π License
Dhan Trading Bot is a sophisticated, production-ready algorithmic trading system specifically designed for MCX Gold futures and options trading. Built with Python 3.13+ and powered by the official DhanHQ API v2.1.0, this system provides institutional-grade trading capabilities for retail and professional traders.
- π― Gold-Focused: Specialized for MCX gold trading with optimized strategies
- β‘ Real-time: WebSocket-based live data streaming with sub-second latency
- π§ Intelligent: Advanced options chain analysis with Greeks calculation
- π‘οΈ Secure: Enterprise-level security with proper credential management
- π Data-Rich: Access to 198,481+ securities across NSE, BSE, MCX exchanges
- π Automated: Fully automated order placement, modification, and risk management
- π Scalable: Modular architecture supporting multiple trading strategies
- Real-time Gold OHLC Data - Live price feeds for MCX Gold December futures
- WebSocket Integration - Ultra-fast market data with ticker, quote, and full packet modes
- Options Chain Analysis - Complete gold options chain with real-time Greeks and OI data
- Automated Order Management - Place, modify, cancel orders programmatically
- Multi-timeframe Analysis - 1min, 5min, 15min, 25min, 60min intraday data
- Historical Data Access - 5-day historical OHLC data for backtesting
- Security Master Database - 198,481+ securities with comprehensive metadata
- Options Greeks Calculator - Delta, Gamma, Theta, Vega calculations
- Volatility Analysis - Implied volatility tracking and alerts
- Volume Profile - Real-time volume analysis and patterns
- Technical Indicators - Built-in support for popular trading indicators
- Position Sizing - Automated position sizing based on risk parameters
- Stop Loss Management - Dynamic stop-loss and take-profit orders
- Portfolio Tracking - Real-time P&L monitoring and reporting
- Margin Calculator - Pre-trade margin requirement calculations
- Kill Switch - Emergency position closure functionality
- Live Market Feed - Real-time price updates via WebSocket
- Order Updates - Live order status notifications
- Performance Analytics - Detailed trading performance metrics
- Alert System - Price, volume, and volatility alerts
- Logging & Audit - Comprehensive trade logging for compliance
| Contract | Security ID | Description | Lot Size |
|---|---|---|---|
| GOLD DEC FUT | 445003 |
Main December contract | 100g |
| GOLDGUINEA DEC | 467740 |
Guinea gold December | 8g |
| GOLDPETAL DEC | 467741 |
Petal gold December | 1g |
| GOLDM DEC | 470295 |
Mini gold December | 10g |
| GOLDTEN DEC | 472782 |
10g gold December | 10g |
- 1,526 Gold Options for December 2024 expiry
- Strike Range: βΉ70,000 to βΉ90,000 (βΉ100 intervals)
- Option Types: Both CALL and PUT options
- Real-time Data: Greeks, Open Interest, Volume, Bid/Ask
- Expiry Dates: Weekly and monthly expiries supported
| Exchange | Securities | Focus Area |
|---|---|---|
| MCX | 26,208 | Commodities (Primary) |
| NSE | 109,646 | Equity & F&O |
| BSE | 62,627 | Equity |
| Requirement | Version | Purpose |
|---|---|---|
| Python | 3.13+ | Core runtime environment |
| pip | Latest | Package management |
| Git | Latest | Version control |
| Virtual Environment | Recommended | Dependency isolation |
# 1. Clone the repository
git clone https://github.com/your-username/dhan-trading-bot.git
cd dhan-trading-bot
# 2. Create virtual environment (RECOMMENDED)
python -m venv venv
# 3. Activate virtual environment
# Linux/Mac:
source venv/bin/activate
# Windows:
venv\Scripts\activate
# 4. Install dependencies
pip install -r requirements.txt
# 5. Verify installation
python -c "from dhanhq import dhanhq; print('β
DhanHQ installed successfully')"dhanhq==2.1.0 # Official DhanHQ API client
pandas>=1.4.3 # Data manipulation and analysis
numpy>=1.26.0 # Numerical computing
websockets>=12.0.1 # WebSocket client for real-time data
pyOpenSSL>=20.0.1 # SSL/TLS support
requests>=2.28.1 # HTTP library for API callspip install dhanhq==2.1.0 pandas numpy websockets pyOpenSSL requestsconda create -n dhan-trading python=3.13
conda activate dhan-trading
pip install -r requirements.txt- Visit DhanHQ Developer Portal
- Create developer account
- Generate API credentials:
- Client ID: Your unique client identifier
- Access Token: Authentication token
Option A: Environment Variables (Recommended)
# Linux/Mac - Add to ~/.bashrc or ~/.zshrc
export DHAN_CLIENT_ID="your_client_id_here"
export DHAN_ACCESS_TOKEN="your_access_token_here"
# Windows - Add to system environment variables
set DHAN_CLIENT_ID=your_client_id_here
set DHAN_ACCESS_TOKEN=your_access_token_hereOption B: Configuration File
# config.py (DO NOT commit to version control)
DHAN_CONFIG = {
"client_id": "your_client_id_here",
"access_token": "your_access_token_here"
}Option C: .env File
# .env file (add to .gitignore)
DHAN_CLIENT_ID=your_client_id_here
DHAN_ACCESS_TOKEN=your_access_token_hereimport os
from dhanhq import DhanContext, dhanhq
# Method 1: Environment Variables
client_id = os.getenv('DHAN_CLIENT_ID')
access_token = os.getenv('DHAN_ACCESS_TOKEN')
# Method 2: Config File
from config import DHAN_CONFIG
client_id = DHAN_CONFIG['client_id']
access_token = DHAN_CONFIG['access_token']
# Initialize DhanHQ client
dhan_context = DhanContext(client_id, access_token)
dhan = dhanhq(dhan_context)# trading_config.py
TRADING_CONFIG = {
# Risk Management
"max_position_size": 5, # Maximum lots per position
"daily_loss_limit": 10000, # Daily loss limit in INR
"stop_loss_percentage": 2.0, # Stop loss as % of entry price
# Gold Specific
"primary_contract": "445003", # GOLD DEC FUT
"lot_size": 100, # 100 grams per lot
"tick_size": 1, # Minimum price movement
# WebSocket Settings
"reconnect_attempts": 5, # Max reconnection attempts
"heartbeat_interval": 30, # Heartbeat interval in seconds
# Logging
"log_level": "INFO", # DEBUG, INFO, WARNING, ERROR
"log_file": "trading.log", # Log file path
}dhan-trading-bot/
βββ π README.md # This comprehensive guide
βββ π requirements.txt # Python dependencies
βββ π .gitignore # Git ignore patterns
βββ π LICENSE # License file
β
βββ π Core Python Files
β βββ dhanhq_client.py # Main DhanHQ API wrapper
β βββ websocket.py # WebSocket implementation
β βββ live_data_fetcher.py # Live data streaming
β βββ gold_ohlc.py # Gold OHLC data fetcher
β βββ gold_option_chain.py # Options chain analysis
β βββ security_search.py # Security lookup utilities
β
βββ π Data Files
β βββ ALL_SECURITY_CODES.json # Complete security database (31MB)
β βββ securities_master.json # Master securities data (25MB)
β
βββ π Documentation
β βββ DHANHQ_API_GUIDE.md # Complete API reference
β βββ SECURITY_CODES.md # Security codes reference
β βββ TRADING_GUIDE.md # Trading strategies guide
β
βββ π§ͺ Examples & Tests
β βββ examples/ # Usage examples
β β βββ basic_trading.py # Basic trading example
β β βββ options_analysis.py # Options chain analysis
β β βββ risk_management.py # Risk management example
β β
β βββ tests/ # Unit tests
β βββ test_client.py # Client tests
β βββ test_websocket.py # WebSocket tests
β βββ test_data.py # Data processing tests
β
βββ π Trading Strategies
β βββ strategies/ # Trading strategy modules
β β βββ momentum.py # Momentum-based strategies
β β βββ mean_reversion.py # Mean reversion strategies
β β βββ options_strategies.py # Options trading strategies
β β
β βββ backtesting/ # Backtesting framework
β βββ backtest_engine.py # Backtesting engine
β βββ performance_metrics.py # Performance analysis
β
βββ π§ Configuration
β βββ config/ # Configuration files
β β βββ trading_config.py # Trading parameters
β β βββ logging_config.py # Logging configuration
β β βββ api_config.py # API settings
β β
β βββ .env.example # Environment variables template
β
βββ π Logs & Data
βββ logs/ # Application logs
β βββ trading.log # Trading activity log
β βββ error.log # Error logs
β βββ performance.log # Performance metrics
β
βββ data/ # Historical data storage
βββ ohlc/ # OHLC data files
βββ options/ # Options data
βββ trades/ # Trade history
from dhanhq import DhanContext, dhanhq
# Initialize client
client_id = "your_client_id"
access_token = "your_access_token"
dhan_context = DhanContext(client_id, access_token)
dhan = dhanhq(dhan_context)
print("π DhanHQ client initialized successfully!")# Fetch Gold December Future OHLC
gold_data = dhan.ohlc_data(
securities = {"MCX_COMM": [445003]} # Gold Dec Future
)
if gold_data['status'] == 'success':
price_data = gold_data['data']['data']['MCX_COMM']['445003']
print(f"π° Gold Price: βΉ{price_data['last_price']}")
print(f"π High: βΉ{price_data['high']}")
print(f"π Low: βΉ{price_data['low']}")
print(f"π Volume: {price_data['volume']}")from dhanhq import MarketFeed
# Setup instruments for Gold December
instruments = [
(MarketFeed.MCX, "445003", MarketFeed.Ticker),
(MarketFeed.MCX, "445003", MarketFeed.Quote),
(MarketFeed.MCX, "445003", MarketFeed.Full)
]
# Connect and stream data
data_feed = MarketFeed(dhan_context, instruments, "v2")
print("π WebSocket connected for Gold December Future")
# Get live data
while True:
data_feed.run_forever()
response = data_feed.get_data()
if response:
print(f"π Live Gold Data: {response}")# Get complete gold options chain
option_chain = dhan.option_chain(
under_security_id=445003,
under_exchange_segment="MCX_COMM",
expiry="2024-12-31"
)
if option_chain['status'] == 'success':
options = option_chain['data']
print(f"π― Found {len(options)} gold options")
# Analyze high volume options
for option in options:
if option['volume'] > 1000:
print(f"π₯ High Volume: {option['name']} - Vol: {option['volume']}")# Buy Gold December Future
order = dhan.place_order(
security_id='445003',
exchange_segment=dhan.MCX_COMM,
transaction_type=dhan.BUY,
quantity=1,
order_type=dhan.MARKET,
product_type=dhan.INTRA,
price=0
)
if order['status'] == 'success':
print(f"β
Order placed successfully! Order ID: {order['data']['orderId']}")
else:
print(f"β Order failed: {order['remarks']}")class GoldMomentumStrategy:
def __init__(self, dhan_client):
self.dhan = dhan_client
self.position_size = 1
self.stop_loss = 2.0 # 2% stop loss
def analyze_momentum(self, price_data):
"""Analyze gold price momentum"""
current_price = price_data['last_price']
high = price_data['high']
low = price_data['low']
# Simple momentum indicator
momentum = (current_price - low) / (high - low)
if momentum > 0.8:
return "BUY"
elif momentum < 0.2:
return "SELL"
else:
return "HOLD"
def execute_trade(self, signal, current_price):
"""Execute trade based on signal"""
if signal == "BUY":
order = self.dhan.place_order(
security_id='445003',
exchange_segment=self.dhan.MCX_COMM,
transaction_type=self.dhan.BUY,
quantity=self.position_size,
order_type=self.dhan.MARKET,
product_type=self.dhan.INTRA,
price=0
)
print(f"π BUY order placed at βΉ{current_price}")
elif signal == "SELL":
order = self.dhan.place_order(
security_id='445003',
exchange_segment=self.dhan.MCX_COMM,
transaction_type=self.dhan.SELL,
quantity=self.position_size,
order_type=self.dhan.MARKET,
product_type=self.dhan.INTRA,
price=0
)
print(f"π SELL order placed at βΉ{current_price}")class GoldStraddleStrategy:
def __init__(self, dhan_client):
self.dhan = dhan_client
def find_atm_options(self, current_price, options_data):
"""Find At-The-Money options"""
atm_strike = round(current_price / 100) * 100
call_option = None
put_option = None
for option in options_data:
if option['strike_price'] == atm_strike:
if option['option_type'] == 'CALL':
call_option = option
elif option['option_type'] == 'PUT':
put_option = option
return call_option, put_option
def execute_straddle(self, call_option, put_option):
"""Execute long straddle strategy"""
# Buy ATM Call
call_order = self.dhan.place_order(
security_id=call_option['security_id'],
exchange_segment=self.dhan.MCX_COMM,
transaction_type=self.dhan.BUY,
quantity=1,
order_type=self.dhan.MARKET,
product_type=self.dhan.INTRA,
price=0
)
# Buy ATM Put
put_order = self.dhan.place_order(
security_id=put_option['security_id'],
exchange_segment=self.dhan.MCX_COMM,
transaction_type=self.dhan.BUY,
quantity=1,
order_type=self.dhan.MARKET,
product_type=self.dhan.INTRA,
price=0
)
print(f"π― Straddle executed: CALL {call_option['strike_price']} + PUT {put_option['strike_price']}")import time
from datetime import datetime
def live_gold_monitor():
"""Monitor gold prices in real-time"""
dhan_context = DhanContext("client_id", "access_token")
dhan = dhanhq(dhan_context)
print("π Starting Gold Price Monitor...")
while True:
try:
# Fetch current gold price
gold_data = dhan.ohlc_data(securities={"MCX_COMM": [445003]})
if gold_data['status'] == 'success':
price_info = gold_data['data']['data']['MCX_COMM']['445003']
current_time = datetime.now().strftime('%H:%M:%S')
print(f"β° {current_time} | π° Gold: βΉ{price_info['last_price']} | "
f"π High: βΉ{price_info['high']} | π Low: βΉ{price_info['low']} | "
f"π Vol: {price_info['volume']}")
# Alert for significant price movements
price_change = price_info['last_price'] - price_info['open']
if abs(price_change) > 500: # Alert for βΉ500+ movement
print(f"π¨ ALERT: Gold moved βΉ{price_change} from open!")
time.sleep(30) # Update every 30 seconds
except KeyboardInterrupt:
print("π Monitor stopped by user")
break
except Exception as e:
print(f"β Error: {e}")
time.sleep(5)
# Run the monitor
live_gold_monitor()def scan_gold_options():
"""Scan gold options for trading opportunities"""
dhan_context = DhanContext("client_id", "access_token")
dhan = dhanhq(dhan_context)
# Get options chain
options = dhan.option_chain(
under_security_id=445003,
under_exchange_segment="MCX_COMM",
expiry="2024-12-31"
)
if options['status'] == 'success':
options_data = options['data']
print("π GOLD OPTIONS SCANNER")
print("=" * 60)
# Find high volume options
high_volume_options = [opt for opt in options_data if opt.get('volume', 0) > 500]
print(f"π High Volume Options ({len(high_volume_options)} found):")
for option in sorted(high_volume_options, key=lambda x: x['volume'], reverse=True)[:10]:
print(f" π― {option['name']} | Vol: {option['volume']} | "
f"LTP: βΉ{option['last_price']} | OI: {option.get('open_interest', 'N/A')}")
# Find low IV options
low_iv_options = [opt for opt in options_data if opt.get('implied_volatility', 100) < 20]
print(f"\nπ Low IV Options ({len(low_iv_options)} found):")
for option in low_iv_options[:5]:
print(f" π {option['name']} | IV: {option.get('implied_volatility', 'N/A')}% | "
f"LTP: βΉ{option['last_price']}")
# Run the scanner
scan_gold_options()class RiskManager:
def __init__(self, dhan_client, max_loss=10000):
self.dhan = dhan_client
self.max_daily_loss = max_loss
self.current_pnl = 0
def check_positions(self):
"""Check current positions and P&L"""
positions = self.dhan.get_positions()
if positions['status'] == 'success':
total_pnl = 0
for position in positions['data']:
pnl = position.get('realized_pnl', 0) + position.get('unrealized_pnl', 0)
total_pnl += pnl
print(f"π {position['security_id']}: P&L βΉ{pnl}")
self.current_pnl = total_pnl
print(f"π° Total P&L: βΉ{total_pnl}")
# Risk check
if total_pnl < -self.max_daily_loss:
print("π¨ RISK ALERT: Daily loss limit exceeded!")
self.emergency_exit()
def emergency_exit(self):
"""Emergency exit all positions"""
print("π EMERGENCY EXIT: Closing all positions...")
positions = self.dhan.get_positions()
if positions['status'] == 'success':
for position in positions['data']:
if position['quantity'] != 0:
# Close position
exit_order = self.dhan.place_order(
security_id=position['security_id'],
exchange_segment=position['exchange_segment'],
transaction_type=self.dhan.SELL if position['quantity'] > 0 else self.dhan.BUY,
quantity=abs(position['quantity']),
order_type=self.dhan.MARKET,
product_type=position['product_type'],
price=0
)
print(f"π Closing position: {position['security_id']}")
# Usage
risk_manager = RiskManager(dhan, max_loss=5000)
risk_manager.check_positions(){
"status": "success",
"data": {
"MCX_COMM": {
"445003": {
"open": 75200.0,
"high": 75450.0,
"low": 75100.0,
"close": 75350.0,
"last_price": 75380.0,
"volume": 12500,
"timestamp": "2024-11-11T15:30:00"
}
}
}
}{
"type": "ticker",
"security_id": "445003",
"ltp": 75380.0,
"change": 180.0,
"change_percent": 0.24,
"volume": 12500,
"timestamp": 1699708200
}{
"security_id": "449537",
"name": "GOLD 31 DEC 75000 CALL",
"strike_price": 75000,
"option_type": "CALL",
"last_price": 1250.0,
"volume": 2500,
"open_interest": 15000,
"implied_volatility": 18.5,
"delta": 0.65,
"gamma": 0.002,
"theta": -12.5,
"vega": 8.2
}from dhanhq import FullDepth
# 20-level market depth
instruments = [(1, "445003")]
depth_feed = FullDepth(dhan_context, instruments)
while True:
depth_feed.run_forever()
depth_data = depth_feed.get_data()
print(f"π Market Depth: {depth_data}")# Get 5-day intraday data
historical = dhan.intraday_minute_data(
security_id="445003",
exchange_segment=dhan.MCX_COMM,
instrument_type="FUTCOM",
from_date="2024-11-06",
to_date="2024-11-11"
)
# Analyze price patterns
import pandas as pd
df = pd.DataFrame(historical['data'])
df['sma_20'] = df['close'].rolling(20).mean()
df['rsi'] = calculate_rsi(df['close'])# Place Good Till Triggered order
forever_order = dhan.place_forever(
security_id="445003",
exchange_segment=dhan.MCX_COMM,
transaction_type=dhan.BUY,
product_type=dhan.CNC,
quantity=1,
price=74000,
trigger_price=74500
)# Calculate required margin
margin = dhan.margin_calculator(
exchange_segment=dhan.MCX_COMM,
security_id="445003",
transaction_type=dhan.BUY,
quantity=1,
product_type=dhan.INTRA,
price=75000
)
print(f"π° Required Margin: βΉ{margin['data']['total_margin']}")class AdvancedRiskManager:
def __init__(self, dhan_client):
self.dhan = dhan_client
self.max_drawdown = 0.05 # 5% max drawdown
self.position_limit = 10 # Max 10 lots
def monitor_risk(self):
"""Comprehensive risk monitoring"""
positions = self.dhan.get_positions()
funds = self.dhan.get_fund_limits()
# Check position limits
total_quantity = sum(abs(pos['quantity']) for pos in positions['data'])
if total_quantity > self.position_limit:
self.reduce_positions()
# Check drawdown
current_balance = funds['data']['available_balance']
if self.calculate_drawdown(current_balance) > self.max_drawdown:
self.emergency_stop()
def set_stop_loss(self, security_id, entry_price, stop_percentage=2.0):
"""Set automatic stop loss"""
stop_price = entry_price * (1 - stop_percentage/100)
stop_order = self.dhan.place_order(
security_id=security_id,
exchange_segment=self.dhan.MCX_COMM,
transaction_type=self.dhan.SELL,
quantity=1,
order_type=self.dhan.STOP_LOSS,
product_type=self.dhan.INTRA,
price=stop_price,
trigger_price=stop_price
)
return stop_orderclass AlertSystem:
def __init__(self):
self.price_alerts = {}
self.volume_alerts = {}
def set_price_alert(self, security_id, target_price, alert_type="ABOVE"):
"""Set price-based alerts"""
self.price_alerts[security_id] = {
'target': target_price,
'type': alert_type,
'active': True
}
def check_alerts(self, market_data):
"""Check and trigger alerts"""
for security_id, alert in self.price_alerts.items():
if not alert['active']:
continue
current_price = market_data.get(security_id, {}).get('ltp', 0)
if alert['type'] == "ABOVE" and current_price >= alert['target']:
self.trigger_alert(f"π¨ {security_id} crossed βΉ{alert['target']}")
alert['active'] = False
elif alert['type'] == "BELOW" and current_price <= alert['target']:
self.trigger_alert(f"π¨ {security_id} fell below βΉ{alert['target']}")
alert['active'] = False
def trigger_alert(self, message):
"""Send alert notification"""
print(f"π’ ALERT: {message}")
# Add email/SMS/webhook notifications hereclass TradingDashboard:
def __init__(self, dhan_client):
self.dhan = dhan_client
def generate_report(self):
"""Generate comprehensive trading report"""
positions = self.dhan.get_positions()
trades = self.dhan.get_trade_history("2024-01-01", "2024-12-31")
report = {
'total_trades': len(trades['data']),
'winning_trades': len([t for t in trades['data'] if t['pnl'] > 0]),
'total_pnl': sum(t['pnl'] for t in trades['data']),
'win_rate': 0,
'avg_profit': 0,
'max_drawdown': self.calculate_max_drawdown(trades['data'])
}
if report['total_trades'] > 0:
report['win_rate'] = report['winning_trades'] / report['total_trades'] * 100
report['avg_profit'] = report['total_pnl'] / report['total_trades']
return report
def display_dashboard(self):
"""Display real-time dashboard"""
report = self.generate_report()
print("π TRADING DASHBOARD")
print("=" * 50)
print(f"π Total Trades: {report['total_trades']}")
print(f"π― Win Rate: {report['win_rate']:.1f}%")
print(f"π° Total P&L: βΉ{report['total_pnl']:,.2f}")
print(f"π Avg Profit: βΉ{report['avg_profit']:,.2f}")
print(f"π Max Drawdown: {report['max_drawdown']:.2f}%")# Solution: Implement reconnection logic
def robust_websocket_connection():
max_retries = 5
retry_count = 0
while retry_count < max_retries:
try:
data_feed = MarketFeed(dhan_context, instruments, "v2")
return data_feed
except Exception as e:
retry_count += 1
print(f"β Connection failed (attempt {retry_count}): {e}")
time.sleep(5)
raise Exception("Max retries exceeded")# Check margin and market status
def safe_order_placement(order_params):
# Check market hours
if not is_market_open():
return {"status": "error", "message": "Market closed"}
# Check available margin
funds = dhan.get_fund_limits()
required_margin = calculate_margin(order_params)
if funds['data']['available_balance'] < required_margin:
return {"status": "error", "message": "Insufficient margin"}
# Place order
return dhan.place_order(**order_params)import time
from functools import wraps
def rate_limit(calls_per_second=10):
"""Rate limiting decorator"""
min_interval = 1.0 / calls_per_second
last_called = [0.0]
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
ret = func(*args, **kwargs)
last_called[0] = time.time()
return ret
return wrapper
return decorator
@rate_limit(calls_per_second=5)
def get_market_data():
return dhan.ohlc_data(securities={"MCX_COMM": [445003]})# Key Gold Security IDs
GOLD_SECURITIES = {
"GOLD_DEC_FUT": "445003", # Main December contract
"GOLDGUINEA_DEC": "467740", # Guinea gold
"GOLDPETAL_DEC": "467741", # Petal gold
"GOLDM_DEC": "470295", # Mini gold
"GOLDTEN_DEC": "472782", # 10g gold
}
# Exchange Segments
EXCHANGES = {
"MCX_COMM": "MCX Commodities",
"NSE_EQ": "NSE Equity",
"NSE_FNO": "NSE F&O",
"BSE_EQ": "BSE Equity"
}# Fork and clone the repository
git clone https://github.com/your-username/dhan-trading-bot.git
cd dhan-trading-bot
# Create development branch
git checkout -b feature/your-feature-name
# Install development dependencies
pip install -r requirements-dev.txt
# Run tests
python -m pytest tests/
# Submit pull request- Follow PEP 8 style guidelines
- Add comprehensive tests for new features
- Update documentation for API changes
- Use meaningful commit messages
- Test with paper trading before live deployment
IMPORTANT RISK DISCLOSURE
This software is provided for educational and research purposes only. Trading in financial markets involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results.
- Market Risk: Commodity prices can be highly volatile
- Leverage Risk: Futures trading involves significant leverage
- Technology Risk: System failures can result in losses
- Regulatory Risk: Trading rules may change
- Liquidity Risk: Markets may become illiquid
- Understand all risks before trading
- Start with paper trading
- Never risk more than you can afford to lose
- Comply with all applicable regulations
- Maintain proper risk management
The authors and contributors are not responsible for any financial losses incurred through the use of this software.
Private License - All Rights Reserved
Copyright (c) 2024 Dhan Trading Bot
This software is proprietary and confidential. Unauthorized copying,
distribution, or use is strictly prohibited.
For licensing inquiries, contact: [[email protected]]
π Happy Trading! π
Built with β€οΈ for the trading community
Last Updated: November 11, 2025 | Version: 2.1.0 | Current Time: Tuesday, 2025-11-11T19:41:48.584+05:30