← Back to Learn
III AdvancedWeek 28 • Lesson 78Duration: 30 min

DOCK Containerization & Docker

Packaging your trading system for reliable, reproducible deployment

Learning Objectives

  • Understand containerization and why it matters for trading
  • Build a Docker container for a trading system
  • Deploy with docker-compose for multi-service setups

Explain Like I'm 5

Containers package your entire application — code, dependencies, configuration — into a single portable unit. "It works on my machine" becomes "it works EVERYWHERE." For trading, this means your engine runs the same whether on your laptop, a VPS, or the cloud. No more "missing library" or "wrong Python version" issues.

Think of It This Way

A container is like a shipping container for code. A shipping container works on any ship, truck, or crane. Similarly, a Docker container runs on any machine with Docker installed. Everything inside is self-contained and standardized.

1Why Containerize Your Trading System

Reasons to containerize V7: 1. Reproducibility: exact same environment everywhere - Same Python version - Same library versions - Same system dependencies (MT5 requires Windows, but Wine works in Linux containers) 2. Deployment: spin up on any VPS in minutes - No manual dependency installation - No configuration drift between environments 3. Scaling: run multiple instances for different accounts - One container per FTMO account - Each with its own configuration 4. Rollback: if an update breaks something, revert to previous container image 5. Monitoring: container orchestration tools provide health checks and automatic restarts Current V7 setup: - Runs directly on Windows (MT5 requires it) - Dependencies managed via pip requirements.txt - Could be containerized with a Windows container or Linux + Wine

2Docker Basics for Trading

Dockerfile — the recipe for building the container: FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["python", "main.py"] docker-compose.yml — multi-container setup: services: engine: build: . environment: - MT5_LOGIN=12345 - MT5_SERVER=FTMO-Demo restart: always dashboard: build: ./dashboard ports: - "8080:8080" redis: image: redis:alpine Key considerations for trading containers: - restart: always — auto-restart on crash - Health checks — verify the engine is running - Volume mounts — persist data and logs outside container - Environment variables — credentials via env vars, NOT in code - Time sync — container clock must match market time

Hands-On Code

Docker Health Check Endpoint

python
from fastapi import FastAPI
from datetime import datetime, timedelta

app = FastAPI()

class HealthChecker:
    """Health check for containerized trading system."""
    
    def __init__(self):
        self.last_cycle = datetime.now()
        self.consecutive_errors = 0
        self.is_trading = False
    
    def update(self, success=True):
        self.last_cycle = datetime.now()
        if success:
            self.consecutive_errors = 0
        else:
            self.consecutive_errors += 1
    
    def is_healthy(self):
        # Unhealthy if no cycle in 20 minutes (M15 + buffer)
        if datetime.now() - self.last_cycle > timedelta(minutes=20):
            return False, "No trading cycle in 20 minutes"
        
        # Unhealthy if too many consecutive errors
        if self.consecutive_errors > 5:
            return False, f"{self.consecutive_errors} consecutive errors"
        
        return True, "Healthy"

health = HealthChecker()

@app.get("/health")
async def healthcheck():
    healthy, message = health.is_healthy()
    if healthy:
        return {"status": "healthy", "message": message, "last_cycle": str(health.last_cycle)}
    else:
        from fastapi.responses import JSONResponse
        return JSONResponse(
            status_code=500,
            content={"status": "unhealthy", "message": message}
        )

Health check endpoints let Docker know if your container is working. If unhealthy, Docker can automatically restart the container. Critical for 24/7 trading systems.

Knowledge Check

Q1.Your trading container crashes at 2 AM. With docker --restart=always, what happens?

Assignment

Create a Dockerfile for a simple trading system. Build the image, run it, and verify the health check endpoint works. Bonus: set up docker-compose with the engine + a Redis cache + a monitoring dashboard.