TradingTeaching Press · Dubai, UAE Trading is high-risk. Check local laws, your residency rules and your finances. Risk warning
🤖 Trading Automation

Deploying Python Trading Bots: Run 24/7 on the Cloud

Learn how to deploy your Python trading bot to run 24/7 on cloud servers with proper monitoring and error handling.

6 min read TradingTeaching Team

Your trading bot needs to run continuously without interruption. This guide covers deploying Python bots to cloud servers for reliable 24/7 operation.

Deployment Options

VPS (Virtual Private Server)

Best for forex trading:

  • Low latency to broker
  • Full control
  • Cost-effective
  • Always running

Popular Providers:

  • DigitalOcean
  • Vultr
  • Linode
  • AWS Lightsail

For trading, avoid serverless:

  • Cold start delays
  • Time limits
  • Connection issues

Preparing Your Bot for Production

Production-Ready Structure

trading_bot/
│
├── bot/
│   ├── __init__.py
│   ├── main.py          # Entry point
│   ├── strategy.py      # Trading logic
│   ├── broker.py        # Broker connection
│   └── risk.py          # Risk management
│
├── config/
│   ├── __init__.py
│   ├── settings.py      # Configuration
│   └── logging_config.py
│
├── logs/
│   └── .gitkeep
│
├── requirements.txt
├── .env.example
├── .gitignore
└── run.sh

Configuration Management

# config/settings.py
import os
from dotenv import load_dotenv

load_dotenv()

class Settings:
    # Broker
    BROKER_ACCOUNT = int(os.getenv('BROKER_ACCOUNT'))
    BROKER_PASSWORD = os.getenv('BROKER_PASSWORD')
    BROKER_SERVER = os.getenv('BROKER_SERVER')

    # Trading
    SYMBOL = os.getenv('SYMBOL', 'EURUSD')
    TIMEFRAME = os.getenv('TIMEFRAME', 'H1')
    RISK_PERCENT = float(os.getenv('RISK_PERCENT', 1.0))

    # System
    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
    HEARTBEAT_INTERVAL = int(os.getenv('HEARTBEAT_INTERVAL', 60))

    @classmethod
    def validate(cls):
        """Validate required settings"""
        required = ['BROKER_ACCOUNT', 'BROKER_PASSWORD', 'BROKER_SERVER']
        for setting in required:
            if getattr(cls, setting) is None:
                raise ValueError(f"Missing required setting: {setting}")

Logging Setup

`python # config/logging_config.py import logging import logging.handlers import os from datetime import datetime

def setup_logging(log_level='INFO'): """Configure logging for production"""

# Create logs directory log_dir = 'logs' os.makedirs(log_dir, exist_ok=True)

# Log filename with date log_file = os.path.join(log_dir, f"bot_{datetime.now():%Y%m%d}.log")

# Configure root logger logger = logging.getLogger() logger.setLevel(getattr(logging, log_level))

# File handler with rotation file_handler = logging.handlers.RotatingFileHandler( log_file, maxBytes=1010241024, # 10MB backupCount=5 ) file_handler.setLevel(logging.DEBUG)

# Console handler console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO)

# Format formatter = logging.Formatter( '%(asctime)s | %(levelname)s | %(name)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) file_handler.setFormatter(formatter) console_handler.setFormatter(formatter)

# Add handlers logger.addHandler(file_handler) logger.addHandler(console_handler)

return logger `

Error Handling

# bot/main.py
import logging
import time
import traceback
from config.settings import Settings
from config.logging_config import setup_logging

logger = logging.getLogger(__name__)

class TradingBot:
    def __init__(self):
        self.running = False
        self.connected = False
        self.retry_count = 0
        self.max_retries = 5

    def connect(self):
        """Connect to broker with retry logic"""
        while self.retry_count < self.max_retries:
            try:
                # Your broker connection code
                logger.info("Connecting to broker...")
                # connection = mt5.initialize()
                self.connected = True
                self.retry_count = 0
                logger.info("Connected successfully")
                return True

            except Exception as e:
                self.retry_count += 1
                wait_time = 2 ** self.retry_count  # Exponential backoff
                logger.error(f"Connection failed: {e}")
                logger.info(f"Retrying in {wait_time} seconds...")
                time.sleep(wait_time)

        logger.critical("Max retries reached. Exiting.")
        return False

    def run(self):
        """Main bot loop"""
        self.running = True

        while self.running:
            try:
                if not self.connected:
                    if not self.connect():
                        break

                # Main trading logic
                self.check_signals()
                self.manage_positions()

                # Heartbeat
                time.sleep(Settings.HEARTBEAT_INTERVAL)

            except KeyboardInterrupt:
                logger.info("Shutdown requested")
                self.running = False

            except Exception as e:
                logger.error(f"Error in main loop: {e}")
                logger.error(traceback.format_exc())
                self.connected = False
                time.sleep(60)  # Wait before retry

        self.shutdown()

    def check_signals(self):
        """Check for trading signals"""
        logger.debug("Checking signals...")
        # Your signal logic

    def manage_positions(self):
        """Manage open positions"""
        logger.debug("Managing positions...")
        # Your position management

    def shutdown(self):
        """Clean shutdown"""
        logger.info("Shutting down bot...")
        # Close connections, save state
        logger.info("Bot stopped")

def main():
    # Setup
    setup_logging(Settings.LOG_LEVEL)
    Settings.validate()

    logger.info("Starting Trading Bot")
    logger.info(f"Symbol: {Settings.SYMBOL}")
    logger.info(f"Timeframe: {Settings.TIMEFRAME}")

    # Run
    bot = TradingBot()
    bot.run()

if __name__ == "__main__":
    main()

Setting Up VPS

1. Create VPS Instance

Choose:

  • Ubuntu 22.04 LTS
  • 2GB RAM minimum
  • Location near broker server

2. Initial Server Setup

# Connect to VPS
ssh root@your_server_ip

# Update system
apt update && apt upgrade -y

# Create non-root user
adduser trader
usermod -aG sudo trader

# Switch to new user
su - trader

3. Install Python Environment

# Install Python
sudo apt install python3.10 python3.10-venv python3-pip -y

# Create project directory
mkdir -p ~/trading_bot
cd ~/trading_bot

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Upgrade pip
pip install --upgrade pip

4. Deploy Bot Code

# Option 1: Git clone
git clone https://github.com/yourusername/trading_bot.git .

# Option 2: SCP upload
# From local machine:
scp -r ./trading_bot trader@your_server_ip:~/trading_bot

5. Install Dependencies

cd ~/trading_bot
source venv/bin/activate
pip install -r requirements.txt

6. Configure Environment

# Copy example env
cp .env.example .env

# Edit with your settings
nano .env

Running as a Service

Create Systemd Service

sudo nano /etc/systemd/system/trading-bot.service

Add:

[Unit]
Description=Trading Bot
After=network.target

[Service]
Type=simple
User=trader
WorkingDirectory=/home/trader/trading_bot
Environment=PATH=/home/trader/trading_bot/venv/bin
ExecStart=/home/trader/trading_bot/venv/bin/python bot/main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Manage Service

# Reload systemd
sudo systemctl daemon-reload

# Enable on boot
sudo systemctl enable trading-bot

# Start service
sudo systemctl start trading-bot

# Check status
sudo systemctl status trading-bot

# View logs
sudo journalctl -u trading-bot -f

# Stop service
sudo systemctl stop trading-bot

# Restart service
sudo systemctl restart trading-bot

Monitoring and Alerts

Health Check Endpoint

# bot/health.py
from flask import Flask, jsonify
import threading

app = Flask(__name__)
bot_status = {"running": False, "last_trade": None, "errors": 0}

@app.route('/health')
def health():
    return jsonify(bot_status)

def start_health_server():
    """Run health server in background"""
    thread = threading.Thread(target=lambda: app.run(host='0.0.0.0', port=5000))
    thread.daemon = True
    thread.start()

Telegram Alerts

# bot/notifications.py
import requests
import logging

logger = logging.getLogger(__name__)

class TelegramNotifier:
    def __init__(self, token, chat_id):
        self.token = token
        self.chat_id = chat_id
        self.base_url = f"https://api.telegram.org/bot{token}"

    def send(self, message):
        """Send Telegram message"""
        try:
            url = f"{self.base_url}/sendMessage"
            data = {
                "chat_id": self.chat_id,
                "text": message,
                "parse_mode": "HTML"
            }
            response = requests.post(url, data=data)
            return response.ok
        except Exception as e:
            logger.error(f"Telegram error: {e}")
            return False

    def send_trade_alert(self, trade_type, symbol, price, sl, tp):
        """Send trade notification"""
        message = f"""
<b>Trade Alert</b>
Type: {trade_type}
Symbol: {symbol}
Price: {price}
SL: {sl}
TP: {tp}
        """
        self.send(message)

    def send_error_alert(self, error):
        """Send error notification"""
        message = f"<b>Bot Error</b>\n{error}"
        self.send(message)

# Usage
notifier = TelegramNotifier(os.getenv('TELEGRAM_TOKEN'),
                           os.getenv('TELEGRAM_CHAT_ID'))
notifier.send_trade_alert('BUY', 'EURUSD', 1.0850, 1.0800, 1.0950)

Log Monitoring with Logwatch

# Install logwatch
sudo apt install logwatch -y

# Configure daily email reports
sudo nano /etc/logwatch/conf/logwatch.conf

Security Best Practices

Firewall Setup

# Enable UFW
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH
sudo ufw allow ssh

# Allow health check (if needed)
sudo ufw allow 5000

# Enable
sudo ufw enable

SSH Security

# Edit SSH config
sudo nano /etc/ssh/sshd_config

# Disable root login
PermitRootLogin no

# Use SSH keys only
PasswordAuthentication no

# Restart SSH
sudo systemctl restart sshd

Environment Security

  • Never commit .env files
  • Use secrets manager for production
  • Rotate API keys regularly
  • Enable 2FA on broker account

Run Script

#!/bin/bash
# run.sh

cd /home/trader/trading_bot
source venv/bin/activate

# Check if already running
if pgrep -f "python bot/main.py" > /dev/null; then
    echo "Bot already running"
    exit 1
fi

# Start bot
python bot/main.py

Key Takeaways

  • Use VPS for 24/7 forex bot operation
  • Implement robust error handling and retries
  • Run as systemd service for auto-restart
  • Set up comprehensive logging
  • Configure Telegram alerts for monitoring
  • Secure your server with firewall and SSH keys
  • Use environment variables for secrets
  • Monitor health and performance

What's Next?

Explore advanced automation topics like multi-currency systems and machine learning integration.


This article is for educational purposes only and does not constitute financial advice.

Risk warning. This is education only, not financial, investment, tax or legal advice, and not a recommendation to buy or sell anything. Trading forex, CFDs, stocks, commodities, futures, options and crypto is high-risk; with leverage you can lose more than you deposit, and most retail traders lose money. Before you trade or invest in any form, check the local laws where you are and the rules of your country of residence, and consider your own financial situation; if in doubt, ask a licensed adviser. Past and tested results, and all examples, are for illustration only and do not guarantee future results.

Get the strategy right before you automate it

An automated system is only as good as the rules behind it. The book series covers building and testing those rules before a line of code is written.

Explore the books