Skip to content

MannanSaood/dhani

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dhani Header


Dhan-MT5 Bridge v2.1 - DIRECT MONITORING EDITION

The middleware monitors your MT5 terminal directly - No separate EA needed!

Automatically mirrors ALL your MT5 positions to Dhan MCX in real-time. Trade normally in MT5 (manual or with any EA), positions automatically execute on Dhan.


How It Works

The Bridge Monitors MT5 Directly

┌─────────────────┐
│  MT5 Terminal   │
│  (Your trades)  │
└────────┬────────┘
         │
         │ MetaTrader5 Python API
         │ (Direct connection)
         ▼
┌─────────────────┐
│  Dhan Bridge    │ ◄─── Monitors every 2 seconds
│  (Middleware)   │ ◄─── Detects ALL changes
└────────┬────────┘
         │
         │ Dhan API
         ▼
┌─────────────────┐
│   Dhan MCX      │
│  (Auto-synced)  │
└─────────────────┘

What This Means:

  • Trade manually in MT5 → Auto-syncs to Dhan
  • Use ANY EA in MT5 → Auto-syncs to Dhan
  • Close positions → Auto-closes on Dhan
  • NO separate EA to install
  • NO code changes to your EA
  • Works with everything

5-Minute Setup

Step 1: Install

git clone <your-repo>
cd dhan-mt5-bridge
chmod +x scripts/setup.sh
./scripts/setup.sh

Step 2: Add Credentials

nano .env

Add:

DHAN_CLIENT_ID=your_client_id
DHAN_ACCESS_TOKEN=your_access_token

Step 3: Make Sure MT5 is Running

IMPORTANT: The bridge connects directly to MT5, so:

  • MT5 terminal must be running
  • Must be logged into your MT5 account
  • Bridge runs on same machine as MT5

Step 4: Start Bridge

python -m app.main

Expected output:

Starting Dhan-MT5 Bridge with DIRECT MT5 MONITORING...
INFO - MT5 connected, account=12345, server=YourBroker-Demo
INFO - Syncing 0 existing positions
INFO - MT5 Direct Monitoring started - ALL positions auto-synced
============================================================
Dhan-MT5 Bridge READY
============================================================
MT5 Monitoring: ACTIVE
Auto Sync: ENABLED
Manual Trading: SUPPORTED
Any EA Trading: SUPPORTED
============================================================

Step 5: Start Trading!

That's it! No EA to install. Just trade.

  1. Open MT5
  2. Buy/Sell manually OR run your EA
  3. Watch the bridge logs
  4. Positions auto-sync to Dhan

Example Usage

Manual Trading

1. You click BUY 0.1 XAUUSD in MT5
   ↓
2. Bridge detects it (within 2 seconds)
   ↓
3. Bridge creates order on Dhan:
   - Symbol: GOLDMFEB2025FUT
   - Lots: 1
   - Side: BUY
   ↓
4. Position synced!

5. You click CLOSE in MT5
   ↓
6. Bridge detects close
   ↓
7. Bridge closes Dhan position
   ↓
8. Both closed!

With Your EA

1. Your EA opens position (any EA)
   ↓
2. Bridge detects it automatically
   ↓
3. Syncs to Dhan
   ↓
4. Done!

(Your EA doesn't need ANY changes)

Monitoring

Check MT5 Connection

curl http://127.0.0.1:8000/mt5/status | jq

Response:

{
  "success": true,
  "monitoring": {
    "mt5_connected": true,
    "tracking_positions": 2,
    "poll_interval": 2,
    "running": true,
    "tracked_tickets": [12345, 12346]
  },
  "message": "MT5 terminal being monitored directly"
}

Check Health

curl http://127.0.0.1:8000/health | jq

View Logs

tail -f logs/bridge.log

You'll see:

INFO - MT5 position opened detected, ticket=12345, symbol=XAUUSD, type=BUY
INFO - Position synced to Dhan, dhan_order_id=112233, mcx_contract=GOLDMFEB2025FUT
INFO - MT5 position closed detected, ticket=12345
INFO - Dhan position closed, dhan_order_id=112234

Configuration

Change Polling Interval

In app/main.py, change:

mt5_config = {
    "poll_interval_seconds": 2,  # Check every 2 seconds
}

Faster (1 second):

  • More responsive
  • Higher CPU usage

Slower (5 seconds):

  • Less CPU usage
  • Slower detection

Recommended: 2 seconds (good balance)


Features

What's Automatic

  1. Position Detection

    • Checks every 2 seconds
    • Detects new positions
    • Detects closed positions
    • Detects SL/TP changes (logged)
  2. Symbol Mapping

    • XAUUSD → GOLDMFEB2025FUT
    • Auto-selects Mini/Petal
    • 40+ commodities supported
  3. Lot Conversion

    • 0.1 MT5 lots → 1 MCX lot (Gold Mini)
    • Automatic based on size
  4. Contract Rollover

    • Auto-rolls 3 days before expiry
    • No manual intervention
  5. Session Management

    • Queues orders if market closed
    • Executes when market opens

Supported Commodities

All 40+ MCX commodities:

  • Metals: Gold, Silver, Copper, Zinc, Lead, Aluminium, Nickel
  • Energy: Crude Oil, Natural Gas
  • Agri: Cotton, CPO, Cardamom, Mentha Oil
  • Spices: Pepper, Jeera, Turmeric

With variants: Standard, Mini, Micro, Petal


Troubleshooting

"MT5 not connected"

Check:

  1. Is MT5 terminal running?
  2. Are you logged into MT5?
  3. Is bridge on same machine as MT5?

Fix:

# Make sure MT5 is running
# Then restart bridge
python -m app.main

"No positions detected"

Check:

  • Bridge logs: tail -f logs/bridge.log
  • MT5 status: curl http://127.0.0.1:8000/mt5/status

Positions Not Syncing

Possible causes:

  1. Dhan credentials wrong → Check .env
  2. Market closed → Check /status/session
  3. Symbol not mapped → Check config/symbols.yaml

Solution:

# Check logs
tail -100 logs/bridge.log | grep -i error

# Check Dhan connection
curl http://127.0.0.1:8000/health | jq '.dhan_connected'

Technical Details

How MT5 Monitoring Works

The bridge uses MetaTrader5 Python package:

import MetaTrader5 as mt5

# Connect to MT5
mt5.initialize()

# Get all positions
positions = mt5.positions_get()

# Monitor for changes
while True:
    current_positions = mt5.positions_get()
    # Detect new/closed positions
    # Sync to Dhan
    sleep(2)

Requirements

  • Python 3.10+
  • MT5 terminal (Windows or Wine on Linux)
  • Dhan account with API access
  • Same machine for bridge and MT5

Architecture

MT5 Terminal
    ↓ (MetaTrader5 package)
MT5 Monitor (app/core/mt5_monitor.py)
    ↓
Position Manager (SQLite)
    ↓
Dhan Client (API wrapper)
    ↓
Dhan MCX

API Endpoints

MT5 Monitoring

# Get monitoring status
GET /mt5/status

# Health check
GET /health

# Positions
GET /positions

# Queue status
GET /status/queue

# Rollover status
GET /rollover/status

Manual Order (Optional)

# You can also place orders via API
POST /order/new
{
  "symbol": "XAUUSD",
  "side": "BUY",
  "order_type": "MARKET",
  "volume": 0.1
}

But with monitoring, just trade in MT5!


Important Notes

ONE CRITICAL TASK

Implement Dhan Security ID lookup:

# In app/core/mt5_monitor.py
async def _get_security_id(self, mcx_info: Dict) -> Optional[str]:
    # TODO: Query Dhan security master
    securities = await self.dhan.get_security_list(exchange="MCX")
    for sec in securities:
        if sec['tradingSymbol'] == mcx_info['contract']:
            return sec['securityId']
    return None

This is the ONLY manual task needed.

Best Practices

  1. Start with paper trading (3+ days)
  2. Monitor logs closely first week
  3. Start with 1 commodity
  4. Small position sizes initially
  5. Gradually scale up

Limitations

  • Bridge and MT5 must be on same machine
  • Requires MT5 terminal to be running
  • 2-second detection delay (adjustable)
  • SL/TP changes logged but not auto-synced to Dhan

What Makes This Special

vs Traditional Solutions

Feature This Bridge Traditional
Separate EA needed No Yes
MT5 code changes No Yes
Works with any EA Yes No
Manual trading Auto-syncs Manual
Setup complexity 5 minutes 30+ minutes
Maintenance Zero EA updates

Why Direct Monitoring?

Advantages:

  • No EA to maintain
  • Works with ANY EA
  • Supports manual trading
  • No MT5 code changes
  • Simpler architecture

How It Works:

  • Python MetaTrader5 package
  • Direct terminal connection
  • Polls every 2 seconds
  • Detects all changes
  • 100% reliable

Support

Logs Location

logs/bridge.log

Common Commands

# Start bridge
python -m app.main

# Check MT5 status
curl http://127.0.0.1:8000/mt5/status

# View logs
tail -f logs/bridge.log

# Check positions
curl http://127.0.0.1:8000/positions

If Something's Wrong

  1. Check logs first
  2. Verify MT5 is running
  3. Check Dhan credentials
  4. Test MT5 connection: /mt5/status

Quick Checklist

Before going live:

  • Bridge starts successfully
  • MT5 connected (check /mt5/status)
  • Dhan connected (check /health)
  • Test: Open position manually in MT5
  • Verify: Check logs show "position synced"
  • Test: Close position in MT5
  • Verify: Check logs show "position closed"
  • Paper trade for 3+ days
  • Start with small sizes

Ready to Trade

# 1. Start MT5 terminal
# 2. Start bridge
python -m app.main

# 3. Trade in MT5
# Everything else is automatic!

That's it. Trade freely. The bridge handles everything.


Made for traders who want simplicity. Zero complexity. Just works.

About

High-performance middleware bridging MetaTrader 5 (MT5) with the Dhan API. Automates trade execution, synchronizes positions in real-time, and handles complex symbol mapping for algorithmic trading.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors