Back to articles
AI & Cloud

Guide to Building a 24/7 AI Trading Bot on VPS: Professional Automation Strategy

A detailed guide to building a 24/7 AI Trading Bot on VPS with professional automated trading strategies, including setup, configuration, API integration, and performance optimization.

DPTCloud Engineering5 min read
Guide to Building a 24/7 AI Trading Bot on VPS: Professional Automation Strategy

Introduction to 24/7 AI Trading Bot on VPS

In the digital era, automating financial trading using AI Trading Bot is becoming a powerful trend. With the ability to operate 24/7, this system enables investors to execute trades quickly, accurately, and without emotional influence. Deploying such a system on a VPS (Virtual Private Server) is an optimal choice due to its stability, high performance, and flexible scalability.

This guide walks you through building a professional AI Trading Bot system that runs continuously on a VPS, integrating automated trading strategies, real-time market analysis, and performance optimization. The guide is suitable for both beginners and experts, with detailed steps, practical configurations, and code examples.

Requirements and Environment Setup

To deploy an AI Trading Bot on a VPS, ensure the following conditions:

  • High-RAM VPS: Use a VPS with at least 8GB RAM (preferably 16GB) to run AI models and process real-time market data. See: High-RAM Cloud VPS for Self-Hosted LLMs & API Gateways
  • Operating System: Ubuntu 20.04/22.04 or Debian 11/12
  • Python 3.9+: Required for bot deployment and AI libraries
  • Trading API: Connect to exchanges (Binance, Bybit, Kraken, etc.) via API
  • AI Libraries: TensorFlow, PyTorch, Scikit-learn, Pandas, NumPy
  • Database: PostgreSQL or SQLite for storing trade history

System Setup and Trading Strategy Integration

First, log in to your VPS via SSH and update the system:

sudo apt update && sudo apt upgrade -y
sudo apt install python3 python3-pip git -y

Create a project directory and initialize a Python virtual environment:

mkdir ai-trading-bot && cd ai-trading-bot
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip

Install required libraries:

pip install requests websocket-client pandas numpy scikit-learn sqlalchemy
pip install tensorflow torch torchvision

To integrate a trading strategy, use a simple model based on moving averages (MA) and RSI:

import pandas as pd
import numpy as np
from ta.momentum import RSIIndicator
from ta.trend import SMAIndicator

def generate_trading_signals(data):
    # Calculate moving averages
    data['SMA_20'] = SMAIndicator(data['close'], window=20).sma_indicator()
    data['SMA_50'] = SMAIndicator(data['close'], window=50).sma_indicator()
    
    # Calculate RSI
    rsi_indicator = RSIIndicator(data['close'], window=14)
    data['RSI'] = rsi_indicator.rsi()
    
    # Generate trading signals
    data['signal'] = 0
    data.loc[data['SMA_20'] > data['SMA_50'], 'signal'] = 1  # Buy
    data.loc[data['SMA_20'] < data['SMA_50'], 'signal'] = -1  # Sell
    data.loc[data['RSI'] < 30, 'signal'] = 1  # Buy when RSI is low
    data.loc[data['RSI'] > 70, 'signal'] = -1  # Sell when RSI is high
    
    return data

To connect to the exchange API, you need an API key and API secret. Example for Binance:

import requests
import time

API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'
BASE_URL = 'https://api.binance.com/api/v3'

def get_market_data(symbol):
    url = f"{BASE_URL}/ticker/price?symbol={symbol}"
    response = requests.get(url)
    return response.json()

def place_order(symbol, side, quantity):
    url = f"{BASE_URL}/order"
    payload = {
        'symbol': symbol,
        'side': side,
        'type': 'MARKET',
        'quantity': quantity
    }
    headers = {
        'X-MBX-APIKEY': API_KEY
    }
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

Execution and System Testing

To test the system, run a simple script to fetch market data and execute trial trades:

def main():
    symbol = 'BTCUSDT'
    while True:
        data = get_market_data(symbol)
        print(f"Current price: {data['price']}")
        
        # Call strategy to generate signals
        signals = generate_trading_signals(data)
        
        # Execute trade if signal is present
        if signals['signal'].iloc[-1] == 1:
            print("Buy signal, executing trade...")
            place_order(symbol, 'BUY', 0.001)
        elif signals['signal'].iloc[-1] == -1:
            print("Sell signal, executing trade...")
            place_order(symbol, 'SELL', 0.001)
        
        time.sleep(60)  # Wait 60 seconds before next check

if __name__ == "__main__":
    main()

To ensure stable operation, use systemd to run the bot as a service:

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

File content:

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

[Service]
Type=simple
User=your_username
WorkingDirectory=/home/your_username/ai-trading-bot
ExecStart=/home/your_username/ai-trading-bot/venv/bin/python /home/your_username/ai-trading-bot/main.py
Restart=always

[Install]
WantedBy=multi-user.target

Start the service:

sudo systemctl daemon-reload
sudo systemctl enable ai-trading-bot.service
sudo systemctl start ai-trading-bot.service

Troubleshooting and Performance Optimization

Common issues when deploying AI Trading Bots:

  • API rate limiting: Use rate limiting and retry logic in your code.
  • Low performance: Optimize AI models, use GPU if available, or switch to lighter models.
  • Connection interruptions: Use WebSocket for real-time market tracking instead of HTTP.

To optimize performance, consider:

  • Using Redis to store temporary market data.
  • Applying scheduling to run the bot during peak trading hours.
  • Integrating logging and alerts to monitor errors.

References

DPTCloud Tier III Infrastructure

High-RAM Cloud VPS Plans Optimized for AI, Databases & Cache

Enterprise RAID 10 NVMe SSDs, CMC & FPT District 9 uplinks with Anycast Anti-DDoS and 99.99% SLA.

View 22 VPS Plans
ECO · vn-02Recommended

VPS-4E

297.000 ₫ / mo

10% VAT included

  • CPU: 4 vCPU
  • RAM: 8 GB
  • SSD: 50 GB NVMe
ECO · vn-02

VPS-5E

614.900 ₫ / mo

10% VAT included

  • CPU: 8 vCPU
  • RAM: 16 GB
  • SSD: 100 GB NVMe
ADVANCED · vn-03Recommended

VPS-4T

548.900 ₫ / mo

10% VAT included

  • CPU: 4 vCPU
  • RAM: 8 GB
  • SSD: 50 GB NVMe

Related Articles

View all
ZaloZalo SupportDiscord0384 753 478