# Production Recommendations

## VPS Deployment

### Laravel Backend VPS
**Recommended Specs:**
- CPU: 2-4 cores
- RAM: 4-8 GB
- Storage: 40-80 GB SSD
- OS: Ubuntu 22.04 LTS
- Location: Same region as MT5 broker server for low latency

### MT5 Python Bridge VPS
**Recommended Specs:**
- CPU: 1-2 cores
- RAM: 2-4 GB
- Storage: 20-40 GB SSD
- OS: Ubuntu 22.04 LTS
- **Critical**: Must be Windows VPS or Linux with Wine for MT5 terminal
- Location: Same as broker server (ideally same datacenter)

### Database Server
**Recommended Specs:**
- CPU: 2-4 cores
- RAM: 8-16 GB
- Storage: 100-200 GB SSD (with backup storage)
- MySQL 8.0+

## Laravel Deployment

### Server Setup
```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install required packages
sudo apt install -y nginx mysql-server php8.2-fpm php8.2-mysql php8.2-mbstring php8.2-xml php8.2-curl php8.2-zip php8.2-bcmath composer git supervisor redis-server

# Install Node.js (for asset compilation if needed)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
```

### Laravel Configuration
```bash
# Clone repository
cd /var/www
git clone your-repo-url ecm-platform
cd ecm-platform

# Install dependencies
composer install --optimize-autoloader --no-dev
npm install && npm run build

# Set permissions
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

# Environment setup
cp .env.example .env
php artisan key:generate
php artisan storage:link
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### Nginx Configuration
```nginx
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/ecm-platform/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

### Supervisor Configuration (Queue Worker)
```ini
[program:ecm-queue-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/ecm-platform/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/ecm-platform/storage/logs/worker.log
stopwaitsecs=3600
```

### Supervisor Configuration (Scheduler)
```ini
[program:ecm-scheduler]
command=php /var/www/ecm-platform/artisan schedule:work
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/ecm-platform/storage/logs/scheduler.log
```

## MT5 Python Bridge Deployment

### Windows VPS Setup (Recommended)
```powershell
# Install Python 3.9+
# Install MetaTrader 5 terminal
# Install Python dependencies
pip install -r requirements.txt

# Configure .env file
cp .env.example .env
# Edit .env with your credentials

# Install NSSM (Non-Sucking Service Manager) to run as Windows service
nssm install MT5SyncBridge "C:\Python39\python.exe" "C:\mt5-sync-bridge\mt5_sync_advanced.py"
nssm set MT5SyncBridge AppDirectory C:\mt5-sync-bridge
nssm set MT5SyncBridge DisplayName "ECM MT5 Sync Bridge"
nssm set MT5SyncBridge Description "Syncs MT5 data to Laravel API"
nssm start MT5SyncBridge
```

### Linux VPS Setup (with Wine)
```bash
# Install Wine
sudo dpkg --add-architecture i386
sudo apt update
sudo apt install -y wine64 wine32

# Install MT5 via Wine
wine mt5setup.exe

# Install Python
sudo apt install -y python3 python3-pip

# Install dependencies
pip3 install -r requirements.txt

# Create systemd service
sudo nano /etc/systemd/system/mt5-sync.service
```

### Systemd Service (Linux)
```ini
[Unit]
Description=MT5 Sync Bridge
After=network.target

[Service]
Type=simple
User=mt5sync
WorkingDirectory=/opt/mt5-sync-bridge
ExecStart=/usr/bin/python3 /opt/mt5-sync-bridge/mt5_sync_advanced.py
Restart=always
RestartSec=10
Environment="PATH=/usr/bin:/usr/local/bin"
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
```

```bash
# Enable and start service
sudo systemctl daemon-reload
sudo systemctl enable mt5-sync
sudo systemctl start mt5-sync
sudo systemctl status mt5-sync
```

## Database Configuration

### MySQL Optimization
```sql
-- Add to my.cnf
[mysqld]
innodb_buffer_pool_size = 4G
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
max_connections = 200
query_cache_size = 0
query_cache_type = 0
```

### Backup Strategy
```bash
# Daily database backup (add to crontab)
0 3 * * * /usr/bin/mysqldump -u backup_user -p'password' ecm_platform | gzip > /backups/ecm_$(date +\%Y\%m\%d).sql.gz

# Keep last 30 days
0 4 * * * find /backups -name "ecm_*.sql.gz" -mtime +30 -delete
```

## Security Recommendations

### Laravel Security
```bash
# Set secure API key in .env
MT5_SYNC_API_KEY=generate-secure-random-key-here

# Use HTTPS with SSL certificate (Let's Encrypt)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

# Configure firewall
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

# Disable debug mode in production
APP_ENV=production
APP_DEBUG=false
```

### API Security
- Use HTTPS for all API calls
- Implement rate limiting (Laravel built-in)
- Use secure API key with rotation policy
- Implement IP whitelist for MT5 sync endpoint
- Validate all incoming data
- Use Laravel Sanctum for authenticated endpoints

## Monitoring & Logging

### Laravel Monitoring
```bash
# Install Laravel Telescope (development)
composer require laravel/telescope
php artisan telescope:install
php artisan migrate

# Install Laravel Horizon (production queue monitoring)
composer require laravel/horizon
php artisan horizon:install
php artisan horizon
```

### Log Monitoring
```bash
# Install fail2ban for security
sudo apt install fail2ban

# Configure log rotation
sudo nano /etc/logrotate.d/ecm-platform

/var/www/ecm-platform/storage/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
}
```

### Health Checks
Create health check endpoint:
```php
// routes/api.php
Route::get('/health', function () {
    return response()->json([
        'status' => 'ok',
        'timestamp' => now(),
        'database' => DB::connection()->getPdo() ? 'connected' : 'disconnected',
        'queue' => Queue::size(),
    ]);
});
```

## Error Recovery Strategy

### Queue Job Failures
- Jobs automatically retry with exponential backoff
- Failed jobs stored in `failed_jobs` table
- Manual retry: `php artisan queue:retry all`
- Monitor failed jobs with Laravel Horizon

### MT5 Sync Failures
- Python bridge has built-in retry logic (3 attempts)
- Automatic reconnection on MT5 disconnect
- Logs all failures with detailed error messages
- Alert on consecutive failures (implement notification)

### Database Connection Failures
- Laravel handles connection retries
- Implement database failover if using replicas
- Monitor connection pool usage

### Profit Distribution Failures
- Transaction rollback on any error
- Status tracking (PENDING → PROCESSING → COMPLETED/FAILED)
- Manual trigger available via API
- Detailed error logging for investigation

## Scaling Considerations

### Horizontal Scaling
- Use load balancer (Nginx/HAProxy) for multiple Laravel instances
- Shared Redis for queue and cache
- Read replicas for database queries
- Separate database for write operations

### Queue Scaling
- Increase supervisor `numprocs` for more workers
- Use Redis cluster for high-volume queues
- Implement queue prioritization

### MT5 Multi-Account
- Python bridge supports multiple accounts
- Each account synced independently
- Parallel sync with rate limiting

## Webhook vs Polling Recommendation

### Recommendation: Polling (Current Implementation)
**Pros:**
- Simpler implementation
- No need for public endpoint exposure
- Better control over sync timing
- Easier to debug and monitor

**Cons:**
- Slight delay in data sync (configurable interval)
- Continuous resource usage

### Alternative: Webhook (Future Enhancement)
**Pros:**
- Real-time sync on trade events
- Lower resource usage
- Instant updates

**Cons:**
- Requires public endpoint
- More complex implementation
- Security concerns (DDoS protection needed)
- MT5 doesn't support native webhooks

**Hybrid Approach:**
- Use polling for regular sync (every 5 minutes)
- Implement webhook for critical events (optional)
- Use polling as fallback mechanism

## Disaster Recovery

### Backup Strategy
1. **Daily database backups** (retention: 30 days)
2. **Weekly full server backups** (retention: 4 weeks)
3. **Offsite backup storage** (S3/Glacier)
4. **Configuration version control** (Git)

### Recovery Procedures
1. Restore database from latest backup
2. Deploy Laravel code from Git
3. Restore environment variables
4. Restart services (Nginx, PHP-FPM, Supervisor)
5. Verify application health
6. Monitor logs for errors

### High Availability (Optional)
- Database replication (master-slave)
- Load balancer with multiple Laravel instances
- Redis cluster for cache/queue
- Multi-region deployment

## Performance Optimization

### Laravel Optimization
```bash
# Optimize composer autoload
composer install --optimize-autoloader --no-dev

# Cache configuration
php artisan config:cache

# Cache routes
php artisan route:cache

# Cache views
php artisan view:cache

# Optimize for production
php artisan optimize
```

### Database Optimization
- Add proper indexes on frequently queried columns
- Use eager loading to prevent N+1 queries
- Implement query caching where appropriate
- Regular database maintenance (ANALYZE TABLE, OPTIMIZE TABLE)

### Queue Optimization
- Use Redis for queue backend (faster than database)
- Implement queue prioritization
- Monitor queue backlog and scale workers accordingly

## Maintenance

### Regular Tasks
- Weekly: Review logs for errors
- Monthly: Database maintenance and optimization
- Quarterly: Security updates and dependency upgrades
- Annually: Full system audit and capacity planning

### Dependency Updates
```bash
# Laravel
composer update

# Python
pip list --outdated
pip install --upgrade package-name
```

## Contact & Support
- Monitor alerts 24/7 during trading hours
- Have on-call rotation for critical issues
- Document all incidents and resolutions
