Skip to content

not-arslan/fs-trender

Repository files navigation

πŸ† Dhan Trading Bot - Professional Gold MCX Trading System

DhanHQ Python MCX License Status

πŸš€ Advanced Algorithmic Trading System for MCX Gold Futures & Options

Powered by DhanHQ API v2.1.0 | Real-time Data | Automated Trading | Risk Management


πŸ“‹ Table of Contents


🎯 Overview

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.

🌟 Why Choose This System?

  • 🎯 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

✨ Key Features

πŸ”₯ Core Trading Features

  • 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

🎯 Advanced Analytics

  • 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

πŸ›‘οΈ Risk & Portfolio Management

  • 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

πŸ“Š Data & Monitoring

  • 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

πŸ“Š Supported Instruments

πŸ₯‡ Gold Futures (MCX)

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

πŸ“ˆ Options Coverage

  • 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 Support

Exchange Securities Focus Area
MCX 26,208 Commodities (Primary)
NSE 109,646 Equity & F&O
BSE 62,627 Equity

πŸ› οΈ Installation

πŸ“‹ Prerequisites

Requirement Version Purpose
Python 3.13+ Core runtime environment
pip Latest Package management
Git Latest Version control
Virtual Environment Recommended Dependency isolation

πŸš€ Quick Installation

# 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')"

πŸ“¦ Dependencies

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 calls

πŸ”§ Alternative Installation Methods

Using pip directly (Global Installation)

pip install dhanhq==2.1.0 pandas numpy websockets pyOpenSSL requests

Using conda (Anaconda/Miniconda)

conda create -n dhan-trading python=3.13
conda activate dhan-trading
pip install -r requirements.txt

πŸ”§ Configuration

πŸ” API Credentials Setup

Step 1: Get DhanHQ API Credentials

  1. Visit DhanHQ Developer Portal
  2. Create developer account
  3. Generate API credentials:
    • Client ID: Your unique client identifier
    • Access Token: Authentication token

Step 2: Secure Credential Storage

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_here

Option 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_here

Step 3: Load Credentials in Code

import 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)

βš™οΈ System Configuration

Trading Parameters

# 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
}

πŸ“ Project Structure

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

πŸš€ Quick Start Guide

🎯 Step 1: Basic Setup

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!")

πŸ“Š Step 2: Get Gold OHLC Data

# 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']}")

πŸ”„ Step 3: Setup WebSocket for Live Data

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}")

πŸ“ˆ Step 4: Analyze Options Chain

# 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']}")

πŸ’Ό Step 5: Place Your First Order

# 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']}")

πŸ“ˆ Trading Strategies

🎯 Strategy 1: Gold Momentum Trading

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}")

🎯 Strategy 2: Options Straddle

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']}")

πŸ” Usage Examples

πŸ“Š Example 1: Live Gold Price Monitor

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()

πŸ“ˆ Example 2: Options Chain Scanner

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()

πŸ›‘οΈ Example 3: Risk Management System

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()

πŸ“Š Market Data Types

OHLC Data Response

{
  "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"
      }
    }
  }
}

WebSocket Live Data

{
  "type": "ticker",
  "security_id": "445003",
  "ltp": 75380.0,
  "change": 180.0,
  "change_percent": 0.24,
  "volume": 12500,
  "timestamp": 1699708200
}

Options Chain Data

{
  "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
}

⚑ Advanced Features

πŸ”₯ Real-time Market Depth

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}")

πŸ“ˆ Historical Data Analysis

# 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'])

🎯 Forever Orders (GTT)

# 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
)

πŸ’° Margin Calculator

# 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']}")

πŸ›‘οΈ Risk Management

πŸ“Š Position Monitoring

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_order

🚨 Alert System

class 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 here

πŸ“± Monitoring & Alerts

πŸ“Š Performance Dashboard

class 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}%")

πŸ”§ Troubleshooting

Common Issues & Solutions

1. WebSocket Connection Failed

# 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")

2. Order Rejection

# 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)

3. Rate Limiting

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]})

πŸ“š API Documentation

πŸ”— Quick Reference Links

πŸ“Š Security IDs Reference

# 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"
}

🀝 Contributing

πŸ”§ Development Setup

# 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

πŸ“ Contribution Guidelines

  • 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

⚠️ Disclaimer

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.

🚨 Key Risks:

  • 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

πŸ“‹ User Responsibilities:

  • 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.


πŸ“„ License

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

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published