# Local Development Setup - MT5 Integration with Laravel

## How Python MetaTrader5 Package Works

The MetaTrader5 Python package is a wrapper around the MetaTrader 5 terminal's API. It allows Python scripts to:

1. **Connect to running MT5 terminal** - The MT5 desktop application must be running
2. **Access trading data** - Account info, positions, orders, history
3. **Execute trades** - Open/close positions, modify orders
4. **Subscribe to symbols** - Get real-time price updates

### Key Concept: It's a Bridge, Not a Direct Connection

```
Python Script → MetaTrader5 Package → MT5 Terminal (Running) → Broker Server
```

The Python package **does not connect directly to the broker server**. It communicates with the locally running MT5 terminal, which then communicates with the broker server.

## Architecture Relationship

```
┌─────────────────────────────────────────────────────────────────┐
│                     Your Windows Laptop                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌──────────────┐         ┌──────────────────┐                  │
│  │ Python Script │────────▶│ MetaTrader5      │                  │
│  │ (mt5_sync.py)│         │ Package          │                  │
│  └──────────────┘         └────────┬─────────┘                  │
│                                    │                            │
│                                    ▼                            │
│                          ┌──────────────────┐                  │
│                          │ MT5 Terminal     │                  │
│                          │ (Must be running)│                  │
│                          └────────┬─────────┘                  │
│                                   │                            │
└───────────────────────────────────┼────────────────────────────┘
                                    │
                                    ▼
                        ┌──────────────────────┐
                        │   Broker Server      │
                        │ (HFMarketsGlobal)    │
                        └──────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│                     Laravel API (Local)                         │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Laravel Server (php artisan serve)                       │  │
│  │ http://127.0.0.1:8000                                    │  │
│  │                                                          │  │
│  │  POST /api/v1/mt5/sync                                   │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
```

## MT5 Path: Required or Optional?

### Default Behavior (No Path)
```python
import MetaTrader5 as mt5

# Uses default MT5 installation path
if mt5.initialize():
    print("Connected to MT5")
else:
    print("Failed to connect")
```

**When this works:**
- MT5 is installed in default Windows location
- 64-bit Python on 64-bit Windows
- Standard MetaQuotes installation

**Default MT5 Paths:**
- 64-bit Windows: `C:\Program Files\MetaTrader 5\terminal64.exe`
- 32-bit Windows: `C:\Program Files (x86)\MetaTrader 5\terminal.exe`

### With Custom Path
```python
import MetaTrader5 as mt5

# Specify custom MT5 installation path
path = "C:\\Users\\YourName\\AppData\\Roaming\\MetaQuotes\\Terminal\\HFMarketsGlobal-Live16\\terminal64.exe"
if mt5.initialize(path=path):
    print("Connected to MT5")
else:
    print("Failed to connect")
```

**When path is necessary:**
- Non-standard MT5 installation location
- Multiple MT5 installations (different brokers)
- Portable MT5 installation
- Custom installation directory
- 32-bit Python on 64-bit Windows (rare)

## Finding Your MT5 Installation Path

### Method 1: Check Desktop Shortcut
1. Right-click MT5 desktop icon
2. Select "Properties"
3. Copy "Target" path
4. Remove quotes and `terminal64.exe` for the path

### Method 2: Check Task Manager
1. Open MT5 terminal
2. Open Task Manager (Ctrl+Shift+Esc)
3. Find "terminal64.exe" or "metaeditor64.exe"
4. Right-click → "Open file location"

### Method 3: Python Script to Detect
```python
import os
import MetaTrader5 as mt5

# Try default first
if mt5.initialize():
    print("Connected using default path")
    mt5.shutdown()
else:
    # Common MT5 paths to try
    paths = [
        r"C:\Program Files\MetaTrader 5\terminal64.exe",
        r"C:\Program Files (x86)\MetaTrader 5\terminal.exe",
        os.path.expandvars(r"%APPDATA%\MetaQuotes\Terminal\HFMarketsGlobal-Live16\terminal64.exe"),
    ]
    
    for path in paths:
        if os.path.exists(path):
            print(f"Found MT5 at: {path}")
            if mt5.initialize(path=path):
                print("Connected successfully!")
                mt5.shutdown()
                break
```

## Debugging mt5.initialize() Failure

### Step 1: Check MT5 Terminal is Running
```bash
# Open Task Manager and verify:
# - terminal64.exe is running
# - You are logged into your trading account
```

### Step 2: Check Last Error
```python
import MetaTrader5 as mt5

if not mt5.initialize():
    print(f"Error code: {mt5.last_error()}")
    # Output format: (error_code, error_message)
```

### Common Error Codes:
- `(-1, 'Terminal not found')` - MT5 not installed or wrong path
- `(-1, 'Terminal busy')` - Another process using MT5
- `(-1, 'Not initialized')` - General initialization failure

### Step 3: Check Python Architecture
```python
import platform
import struct

print(f"Python version: {platform.python_version()}")
print(f"Python architecture: {platform.architecture()[0]}")
print(f"OS: {platform.system()} {platform.release()}")
print(f"Is 64-bit: {struct.calcsize('P') * 8} bit")
```

**Requirement:** 64-bit Python on 64-bit Windows for 64-bit MT5

### Step 4: Check MT5 Version
```python
import MetaTrader5 as mt5

print(f"MetaTrader5 package version: {mt5.__version__}")
```

**Minimum required:** MetaTrader5 package version 5.0.37+

## Local Development Architecture

```
d:/Trade/FTP/
├── app/                          # Laravel Application
│   ├── Http/Controllers/Api/
│   │   └── Mt5SyncController.php
│   ├── Services/
│   │   ├── Mt5SyncService.php
│   │   └── ProfitSharingService.php
│   └── Jobs/
│       └── ProcessMt5Sync.php
│
├── python-mt5-bridge/             # Python MT5 Sync Service
│   ├── mt5_sync.py                # Basic sync script
│   ├── mt5_sync_advanced.py       # Advanced with retry logic
│   ├── test_mt5_connection.py     # Test script
│   ├── .env                       # Python environment variables
│   ├── requirements.txt           # Python dependencies
│   └── logs/                      # Python logs
│       └── mt5_sync.log
│
├── storage/                       # Laravel storage
│   └── logs/                      # Laravel logs
│       └── laravel.log
│
├── .env                           # Laravel environment variables
└── LOCAL_DEVELOPMENT_SETUP.md     # This file
```

## Best Practice Setup for Local Laptop Development

### 1. Install Prerequisites

**Python (64-bit):**
```bash
# Download from python.org
# Ensure 64-bit version is installed
python --version
python -c "import struct; print(f'{struct.calcsize(\"P\") * 8} bit')"
```

**MetaTrader 5 Terminal:**
- Download from your broker (HFMarkets)
- Install to standard location
- Log in to your trading account
- Keep terminal running during development

**Laravel:**
```bash
composer install
php artisan key:generate
php artisan migrate
```

### 2. Configure Laravel

**Edit .env:**
```env
APP_NAME=ECM
APP_ENV=local
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ecm_platform
DB_USERNAME=root
DB_PASSWORD=

QUEUE_CONNECTION=database

MT5_SYNC_API_KEY=mt5-bridge
```

**Run migrations:**
```bash
php artisan migrate
```

### 3. Configure Python MT5 Bridge

**Create python-mt5-bridge/.env:**
```env
LARAVEL_API_URL=http://127.0.0.1:8000/api/v1/mt5/sync
API_KEY=mt5-bridge
SYNC_INTERVAL_SECONDS=300
```

**Install Python dependencies:**
```bash
cd python-mt5-bridge
pip install -r requirements.txt
```

### 4. Start Laravel Server
```bash
# Terminal 1
cd d:/Trade/FTP
php artisan serve
```

### 5. Start Queue Worker (Optional)
```bash
# Terminal 2
cd d:/Trade/FTP
php artisan queue:work
```

### 6. Test Python MT5 Connection
```bash
# Terminal 3
cd python-mt5-bridge
python test_mt5_connection.py
```

### 7. Run Python Sync Service
```bash
# Terminal 3 (after test passes)
python mt5_sync.py
```

## Example Python Test Script

Create `python-mt5-bridge/test_mt5_connection.py`:

```python
"""
Test script to verify MT5 connection and data retrieval
"""

import MetaTrader5 as mt5
import sys
from datetime import datetime

def test_mt5_connection():
    print("=" * 60)
    print("MT5 Connection Test")
    print("=" * 60)
    
    # Test 1: Initialize MT5
    print("\n[1] Testing MT5 initialization...")
    if not mt5.initialize():
        error = mt5.last_error()
        print(f"❌ Failed to initialize MT5: {error}")
        print("\nTroubleshooting:")
        print("  1. Ensure MT5 terminal is running")
        print("  2. Ensure you are logged into your trading account")
        print("  3. Check if 64-bit Python is installed")
        return False
    print("✅ MT5 initialized successfully")
    
    # Test 2: Get MT5 version
    print("\n[2] Getting MT5 version...")
    print(f"   MetaTrader5 package version: {mt5.__version__}")
    print(f"   Terminal info: {mt5.terminal_info()}")
    
    # Test 3: Get account info
    print("\n[3] Getting account information...")
    account_info = mt5.account_info()
    if account_info is None:
        print("❌ Failed to get account info")
        mt5.shutdown()
        return False
    
    print(f"   Account: {account_info.login}")
    print(f"   Name: {account_info.name}")
    print(f"   Server: {account_info.server}")
    print(f"   Balance: {account_info.balance}")
    print(f"   Equity: {account_info.equity}")
    print(f"   Currency: {account_info.currency}")
    print(f"   Leverage: {account_info.leverage}")
    print("✅ Account info retrieved successfully")
    
    # Test 4: Get open positions
    print("\n[4] Getting open positions...")
    positions = mt5.positions_get()
    if positions is None:
        print("❌ Failed to get positions")
        mt5.shutdown()
        return False
    
    print(f"   Total open positions: {len(positions)}")
    for i, pos in enumerate(positions[:5], 1):  # Show first 5
        print(f"   [{i}] {pos.symbol} - {pos.type} - Volume: {pos.volume} - Profit: {pos.profit}")
    print("✅ Positions retrieved successfully")
    
    # Test 5: Get closed positions (last 10)
    print("\n[5] Getting recent closed positions...")
    from datetime import timedelta
    to_date = datetime.now()
    from_date = to_date - timedelta(days=7)
    
    history = mt5.history_deals_get(from_date, to_date)
    if history is None:
        print("❌ Failed to get history")
        mt5.shutdown()
        return False
    
    print(f"   Closed positions in last 7 days: {len(history)}")
    print("✅ History retrieved successfully")
    
    # Cleanup
    print("\n[6] Shutting down MT5 connection...")
    mt5.shutdown()
    print("✅ MT5 shutdown successful")
    
    print("\n" + "=" * 60)
    print("✅ All tests passed! MT5 connection is working.")
    print("=" * 60)
    return True

if __name__ == "__main__":
    try:
        success = test_mt5_connection()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n❌ Test failed with exception: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
```

## Troubleshooting Checklist

### MT5 Terminal
- [ ] MT5 terminal is running (check Task Manager)
- [ ] You are logged into your trading account
- [ ] Account has active trading permissions
- [ ] Terminal is not in "Read Only" mode

### Python Environment
- [ ] Python 3.9+ installed (64-bit)
- [ ] MetaTrader5 package installed: `pip install MetaTrader5`
- [ ] Package version >= 5.0.37: `pip show MetaTrader5`
- [ ] Running in correct virtual environment (if used)

### Architecture Compatibility
- [ ] 64-bit Python on 64-bit Windows
- [ ] Python architecture matches MT5 architecture
- [ ] Check with: `python -c "import struct; print(struct.calcsize('P') * 8)"`

### Installation Path
- [ ] MT5 installed in standard location
- [ ] Or custom path specified in mt5.initialize(path="...")
- [ ] Path points to terminal64.exe (not just folder)
- [ ] Path uses double backslashes or raw strings: `r"C:\path\to\terminal64.exe"`

### Network/Broker
- [ ] Internet connection is active
- [ ] Broker server is reachable
- [ ] Trading account is active (not suspended)
- [ ] No firewall blocking MT5 terminal

### Laravel API
- [ ] Laravel server running: `php artisan serve`
- [ ] Correct API URL in Python .env
- [ ] API key matches between Python and Laravel
- [ ] Route cache cleared: `php artisan route:clear`

## Future Production Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                    Windows VPS (MT5)                            │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────┐         ┌──────────────────┐                  │
│  │ Python Sync  │────────▶│ MetaTrader5      │                  │
│  │ Service      │         │ Package          │                  │
│  │ (systemd/NSSM)│        └────────┬─────────┘                  │
│  └──────────────┘                 │                            │
│                                   ▼                            │
│                          ┌──────────────────┐                  │
│                          │ MT5 Terminal     │                  │
│                          │ (Always running) │                  │
│                          └────────┬─────────┘                  │
└───────────────────────────────────┼────────────────────────────┘
                                   │
                                   │ HTTPS
                                   ▼
┌─────────────────────────────────────────────────────────────────┐
│                   Linux VPS (Laravel API)                       │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Nginx                                                    │  │
│  │   │                                                      │  │
│  │   ▼                                                      │  │
│  │ PHP-FPM ◀──── Laravel Application ◀──── MySQL            │  │
│  │   │              (Queue Workers)         (Database)      │  │
│  │   ▼                                                      │  │
│  │ Redis (Queue/Cache)                                      │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                  │
│  POST https://api.your-domain.com/api/v1/mt5/sync              │
└─────────────────────────────────────────────────────────────────┘
```

### Production Recommendations

**Windows VPS for MT5:**
- Windows Server 2019/2022
- 2-4 CPU cores
- 4-8 GB RAM
- 40 GB SSD
- MT5 terminal installed
- Python sync service as Windows service (NSSM)
- Same datacenter as broker for low latency

**Linux VPS for Laravel:**
- Ubuntu 22.04 LTS
- 2-4 CPU cores
- 4-8 GB RAM
- 40-80 GB SSD
- Nginx + PHP-FPM
- MySQL 8.0
- Redis
- Supervisor for queue workers

**Security:**
- HTTPS with SSL certificate
- API key authentication
- IP whitelist for MT5 sync endpoint
- Firewall rules
- Regular backups

**Monitoring:**
- Laravel logs monitoring
- Python service monitoring
- Database backups
- Uptime monitoring
- Alert system for failures
