Run a crypto trading bot 24/7 on a VPS: uptime, latency and security basics
A trading bot on a laptop stops when the lid closes, the Wi-Fi drops or the OS decides to update. A small Linux VPS fixes the uptime problem, but it adds new ones: the bot holds exchange API keys on a machine that is exp
A trading bot on a laptop stops when the lid closes, the Wi-Fi drops or the OS decides to update. A small Linux VPS
fixes the uptime problem, but it adds new ones: the bot holds exchange API keys on a machine that is exposed to the
internet around the clock.
This guide covers the infrastructure side only: keeping the process alive, keeping keys safe, keeping the clock
right, and knowing when something breaks. It is not financial advice and says nothing about strategies. The
examples use a Python bot on Ubuntu 24.04 or Debian 12; the same structure works for Node.js or Go.
1. Start from a hardened server
Before the bot, the basics: security updates, SSH keys only, a firewall that allows SSH and nothing else (a bot
makes outgoing connections; it rarely needs any incoming port), and fail2ban. The open-source
vps-first-steps script does this in one run:
curl -fsSLO https://raw.githubusercontent.com/phantomvps/vps-first-steps/main/vps-first-steps.sh
less vps-first-steps.sh
sudo bash vps-first-steps.sh --user deploy
2. A dedicated user and a virtual environment
Never run the bot as root. Give it its own system user with no login shell:
sudo apt install -y python3-venv git
sudo useradd --system --create-home --home-dir /opt/bot --shell /usr/sbin/nologin bot
sudo -u bot git clone https://example.com/you/your-bot.git /opt/bot/app
sudo -u bot python3 -m venv /opt/bot/venv
sudo -u bot /opt/bot/venv/bin/pip install -r /opt/bot/app/requirements.txt
sudo -u bot mkdir -p /opt/bot/data
Ubuntu 24.04 ships Python 3.12 and Debian 12 ships Python 3.11. Both refuse pip install into the system Python
(PEP 668), which is another reason to use a venv.
3. API keys: least privilege, outside the code
The keys are the most valuable thing on the server. Three rules:
- Create keys with trading permission only. No withdrawal permission, ever. If the key leaks, the attacker can place bad trades but cannot move funds out.
- Restrict the key to your server's IP in the exchange's API settings, if the exchange supports an IP allowlist. A stolen key then does not work from anywhere else.
- Keep keys out of the repository. Put them in an environment file that only root can read; systemd passes them to the process.
sudo mkdir -p /etc/bot
sudo install -m 600 -o root -g root /dev/null /etc/bot/bot.env
sudo nano /etc/bot/bot.env
EXCHANGE_API_KEY=...
EXCHANGE_API_SECRET=...
4. A systemd unit that restarts and contains the bot
Create /etc/systemd/system/bot.service:
[Unit]
Description=Trading bot
Wants=network-online.target
After=network-online.target time-sync.target
StartLimitIntervalSec=300
StartLimitBurst=10
[Service]
Type=simple
User=bot
Group=bot
WorkingDirectory=/opt/bot/app
EnvironmentFile=/etc/bot/bot.env
ExecStart=/opt/bot/venv/bin/python -u main.py
Restart=always
RestartSec=10
# Containment
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/bot/data
PrivateTmp=true
PrivateDevices=true
MemoryMax=1G
[Install]
WantedBy=multi-user.target
What it does:
-
Restart=alwayswithRestartSec=10restarts the bot after a crash or an unhandled exception, ten seconds later. -
StartLimitIntervalSec/StartLimitBurst(these belong in[Unit]) stop a crash loop: more than 10 restarts in 5 minutes and systemd gives up, which your monitoring should notice. -
ProtectSystem=strictmakes the whole filesystem read-only for the bot exceptReadWritePaths. A compromised dependency cannot overwrite system files or the bot's own code. -
MemoryMaxstops a memory leak from taking the whole server down; the bot is killed and restarted instead. -
-umakes Python output unbuffered, so logs appear immediately.
Enable it:
sudo systemctl daemon-reload
sudo systemctl enable --now bot
systemctl status bot
journalctl -u bot -f
Make sure the bot handles SIGTERM (sent on systemctl stop and on reboot) by cancelling open work cleanly, and
that it can resume from state in /opt/bot/data after a restart, rather than trading as if it had just started.
5. Keep the clock right
Exchange APIs sign requests with a timestamp and reject requests whose time is too far from the server's clock. A
drifting VPS clock shows up as sudden authentication errors.
timedatectl
You want System clock synchronized: yes. Ubuntu 24.04 and Debian 12 use systemd-timesyncd by default. If you
prefer chrony, which corrects drift faster and reports more detail:
sudo apt install -y chrony # replaces systemd-timesyncd
chronyc tracking # "System time" offset should be milliseconds or less
6. Measure latency to the exchange, then choose the location
For most bots a few tens of milliseconds make no difference. If yours is latency-sensitive, measure from candidate
locations instead of guessing. curl prints a breakdown:
curl -o /dev/null -s -w 'dns %{time_namelookup} tcp %{time_connect} tls %{time_appconnect} total %{time_total}\n' \
https://api.your-exchange.example/api/v3/time
Run it 20 times and look at the spread, not one number. tcp minus dns is roughly one network round trip. Exchanges
publish where their API endpoints are hosted, or you can infer it with mtr; a server in the same region usually
gives the lowest and most stable round trip.
7. Know when it stops
A bot that has silently stopped trading is worse than one that crashed loudly. Use a heartbeat: the bot calls a
URL every few minutes, and a monitor alerts you when the calls stop. A self-hosted Uptime Kuma instance (on a
different server) with a "push" monitor does this, as do hosted heartbeat services.
import requests, time
HEARTBEAT_URL = "https://status.example.org/api/push/abc123"
def heartbeat():
try:
requests.get(HEARTBEAT_URL, timeout=5)
except requests.RequestException:
pass # never let monitoring crash the bot
Call it from the main loop after a successful cycle, not from a separate thread, so it proves the loop is running.
8. Logs, disk and memory
-
Cap journald so logs never fill the disk. In
/etc/systemd/journald.confsetSystemMaxUse=500M, thensudo systemctl restart systemd-journald. - Add swap on a small VPS so a short memory spike does not trigger the kernel's OOM killer:
sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
-
Back up
/opt/bot/dataand your configuration off the server. Never back up the API keys in plain text.
9. Updating safely
sudo systemctl stop bot
sudo -u bot git -C /opt/bot/app pull
sudo -u bot /opt/bot/venv/bin/pip install -r /opt/bot/app/requirements.txt
sudo systemctl start bot && journalctl -u bot -n 50
Pin dependency versions in requirements.txt. An unpinned library update is a common way for a working bot to
break at 3 a.m.
Checklist
- [ ] Server hardened, no inbound ports except SSH
- [ ] Bot runs as its own user, in a venv
- [ ] API keys: trade-only, IP-restricted, in a 0600 env file
- [ ] systemd unit with restart limits and containment
- [ ] Clock synchronised
- [ ] Latency measured from the chosen location
- [ ] Heartbeat monitor on another machine
- [ ] Journald capped, swap added, data backed up
Where to run it
I work with PhantomVPS: VPS plans with root access, paid in Monero, Bitcoin, Litecoin, USDT, USDC, SOL or TRX, with
no ID documents needed. Our use cases page lists what you can run, and the
test IPs let you measure latency from each location before you order.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes â full credit and traffic to the original publisher.