SSD Nodes Learn Hosting plans →
How to do am Matt ConnorBy Matt Connor

VPS for trading bot: wetin really matter

Know wetin trading bot truly need from VPS: systemd restart, correct clock, safe API keys, heartbeats, and why low latency no be everything.

Trading bot dey need wetin from VPS

People dey judge VPS for trading bots with four things: process go come back after e die? Clock dey correct? API (application programming interface) keys hard to thief? And you go know when e stop? Raw speed no too high for that list for retail bot, because the slow part for your order path na your broker and the distance go broker, no be host wey dey run your Python.

This na engineering guide. Nothing for here be financial advice, and we no dey discuss any strategy.

Uptime na restart discipline, no be number for sales page

Uptime commitments wey providers advertise dey differ. AWS specify at least 99.5 percent for one EC2 instance and 99.99 percent for qualifying deployments across multiple availability zones. Those commitments cover infrastructure availability, no be your bot health. Bot fit die from unhandled exception, websocket wey never reconnect, or OOM (out of memory) killer, while server remain up throughout. So the useful question be wetin go happen for the ten seconds after your process exit.

Run the bot as systemd service and make the init system handle the restart. Unit file dey do this.

[Unit]
Description=Trading bot
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=0

[Service]
Type=simple
User=bot
WorkingDirectory=/opt/tradingbot
EnvironmentFile=/etc/tradingbot/api.env
ExecStart=/opt/tradingbot/venv/bin/python -m tradingbot
Restart=always
RestartSec=10
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/tradingbot

[Install]
WantedBy=multi-user.target

StartLimitIntervalSec=0 na the line wey people dey miss. Upstream systemd defaults allow 5 starts for 10 seconds, including the initial start and manual starts; manager configuration fit override those defaults. When the limit reach, automatic restart attempts stop, but you fit start the unit manually or through timer or socket after the interval pass. Setting am to 0 disable the rate limit, so bot wey dey crash-loop go continue to try instead of going quiet. RestartSec=10 stop that loop from hammering the exchange with reconnects.

Check the file before you trust am, then start am:

sudo systemd-analyze verify /etc/systemd/system/tradingbot.service
sudo systemctl daemon-reload
sudo systemctl enable --now tradingbot
systemctl status tradingbot

enable na the part wey survive reboot, and kernel updates mean reboot. To see whether the bot don dey die quietly, ask systemd for the restart counter:

systemctl show tradingbot -p NRestarts
journalctl -u tradingbot --since "24 hours ago" | tail -50

NRestarts=0 count automatic restart jobs since the counter last reset; e no prove say the bot healthy or say e never crash for one week. Manual restarts and systemctl reset-failed reset the counter, and hung bot fit still show zero. NRestarts=812 count 812 restart jobs, no be successful exchange reconnections or trades, and e no talk when dem happen. Check the journal for the timing and cause, including failures wey happen before the bot connect. Full unit file anatomy, including timers for scheduled jobs like daily report, dey covered for running a program as systemd service.

Set clock to UTC and prove say e don synchronise

Exchange APIs dey use timestamps to validate signed requests; Binance Spot dey use 5-second receive window by default and e dey reject timestamps wey dey at least 1 second ahead of server time. Clock wey dey drift dey produce errors wey look like authentication failures, so people fit rotate keys for hours before dem check time. For Binance-style APIs, the message dey literal: Timestamp for this request was 1000ms ahead of the server's time.

Set the server to UTC. Local time zones fit introduce daylight saving jumps for displayed times; Unix timestamps wey APIs dey use no dey jump when display timezone change.

sudo timedatectl set-timezone UTC
timedatectl

Ubuntu dey use chrony by default from 25.10 onward; older installations fit use systemd-timesyncd, wey be SNTP (simple network time protocol) client. systemd-timesyncd dey adjust clock, but e no fit poll multiple servers at once to detect incorrect time source. Use chrony instead:

sudo apt update && sudo apt install -y chrony
sudo systemctl enable --now chrony
chronyc tracking
chronyc sources -v

The line to read from chronyc tracking na System time, for example System time : 0.000031415 seconds fast of NTP time. Small value show say small correction remain for chrony's NTP clock; check synchronisation, Root delay and Root dispersion too before you judge accuracy. If e read Leap status : Not synchronised, chrony no dey synchronise, even if servers don respond; measurements fit get rejected because dem no accurate enough. Wait one minute, then check again before you touch firewall rules.

Keep API keys away from the places wey you dey copy

If exchange key leak, e worse pass SSH key leak, because withdrawal permission fit turn am to money immediately. Two habits fit cover most of the risk.

First, never give bot key withdrawal permission. If the exchange support am, bind the key to your server IP address. Na this control make stolen key almost useless.

Second, keep the secret outside the code directory. Anything wey dey inside /opt/tradingbot go enter git repository or backup archive sooner or later. Put am for file wey root own and systemd dey read:

sudo install -d -m 750 -o root -g bot /etc/tradingbot
sudo install -m 640 -o root -g bot /dev/null /etc/tradingbot/api.env
sudo nano /etc/tradingbot/api.env

The file get plain KEY=value lines, without quotes and without export. Mode 640 give root owner read/write access. E give members of group bot read access. Other users get no permission. Verify am with sudo -u bot cat /etc/tradingbot/api.env. Then test am with unprivileged user wey no dey group bot. The access must fail with Permission denied.

The bot itself no suppose run as root or as your login user. Create system account with nologin shell and /var/lib/tradingbot as the home directory before you start the service or create files wey group bot own:

sudo useradd --system --shell /usr/sbin/nologin --home-dir /var/lib/tradingbot --create-home bot

The reason for each of those flags, and wetin ProtectSystem=strict really cover, dey for running services as an unprivileged user. The remaining server baseline, SSH keys and firewall, belong for the first ten minutes on a new VPS.

Find out say e dey down before your broker find out

systemctl status dey show say the process dey run. E no mean say the bot dey do anything. Process wey stuck for retry loop against dead websocket fit pass the process checks for the unit above.

Use heartbeat instead. Uptime Kuma get push monitors: e expect your bot to call URL for schedule, and e go alert when the call stop to arrive. Put the call for the end of your main loop, after the part wey prove say the bot dey alive, like successful market data read.

curl -fsS "http://monitor.example.com:3001/api/push/YOUR_TOKEN?status=up&msg=loop_ok"

Set the monitor interval to roughly twice your loop time so normal jitter no go page you. Run the monitor for different server from the bot, because monitor wey die together with the thing wey e dey watch no go report anything. Setup dey covered for self-hosted status monitoring with Uptime Kuma.

Add disk alert too. Bot wey dey write verbose logs fit fill root filesystem within weeks, and full disk go stop database write, no be network call, so the symptoms go strange. journalctl --vacuum-time=14d and one SystemMaxUse= line for /etc/systemd/journald.conf go keep the journal bounded.

The honest part: latency mostly no dey come from your host

Na for here market for trading VPS products stop to be technical. Marketing pages dey quote sub-millisecond figures and make am look like na the host dey between you and successful fill. For almost every retail bot, e no be so.

Your order dey travel from the bot go exchange or broker endpoint through public internet. Physical distance and peering between your provider and their provider mostly dey determine that path. Then broker own systems add their queue, risk checks, and rate limits.

Measure am instead of guessing. curl dey report connection time and first-byte time for real endpoint:

curl -s -o /dev/null -w 'dns=%{time_namelookup}s connect=%{time_connect}s ttfb=%{time_starttransfer}s\n' \
  https://api.kraken.com/0/public/Time
mtr -rwzc 100 api.kraken.com

Run this from candidate server before you commit. If connect na 0.180 seconds, e include DNS resolution and TCP connection; e no prove which continent you dey. If connect na 0.004 seconds and ttfb na 0.140 seconds, the difference include TLS setup, request transmission, network delays, and server processing. Changing host fit affect some of these parts, so compare measurements from candidate locations.

So when host matter? E matter when you dey colocated or cross-connected to the venue and you dey compete for queue position. Na different business be that, with different budget. E also matter when your own code na the bottleneck. For example, bot wey dey recompute indicators over full history every tick fit use 200 milliseconds of CPU per loop. Na real latency be that, and you fit control am for free. Profile the loop before you start looking for faster server.

The things wey matter for the host you choose na geography, stable networking, and enough memory so OOM killer no ever get chance to act. Add more memory if you dey keep tick history for local database.

One short checklist before you go live

  1. systemctl is-enabled tradingbot dey print enabled, and the service still dey run after sudo reboot.
  2. chronyc tracking dey report synchronisation, system time offset wey dey below some milliseconds, plus root delay and dispersion wey dey within your timing budget.
  3. The API key get trading permission, e no get withdrawal permission, and e get IP allowlist if the exchange provide one.
  4. If you kill the process with sudo systemctl kill -s SIGKILL tradingbot, e dey come back after the RestartSec delay and startup time.
  5. The heartbeat monitor dey page you after the configured interval, and e dey retry when you deliberately stop the bot.
  6. Logs get limit, and root filesystem still get enough free space for df -h.

Run everything for the exchange sandbox or paper mode for one week before you use real funds. Every item above go fail at least once during that week. Na that be the reason for the week.

FAQ

Bot wey dey trade need low-latency or bare metal server?

Na only if you dey compete for execution speed against other automated participants for the same venue. Normally, that one mean colocation instead of general purpose VPS. For retail bot, geography and the broker own processing dey mostly determine round-trip time. So choose server wey dey near the API endpoint, then measure with curl and mtr before you pay for anything faster.

How much RAM and CPU trading bot need?

Most single-strategy bots depend on network and dey idle between events. Memory fit become the limit when you keep tick history inside the process or run local database. So monitor free -h and the journal for OOM kill messages instead of guessing.

Why exchange API dey reject my requests with timestamp error?

The request timestamp dey outside the time window wey the exchange accept. Clock drift and request delays both matter. Install chrony. Confirm say chronyc tracking show small System time offset and synchronised leap status. Check root delay and dispersion too. Setting the machine to UTC make displayed times consistent, but e no correct clock drift. Rotating the API key no go fix clock problem.

How I fit stop my bot from dying overnight without me knowing?

Run am under systemd with Restart=always and StartLimitIntervalSec=0, so crash loop go keep retrying instead of hitting the start rate limit. Then add heartbeat wey the bot go send at the end of each successful loop. Restart dey handle the process. Heartbeat dey catch the case where the process dey alive but stuck.

I fit run the bot and my monitoring for the same VPS?

You fit, but the monitoring go lie to you on the day wey e matter, because outage wey bring down the bot go also bring down the monitor. Keep alerting for separate machine, preferably with different provider or region. Use the bot server only for the bot and its logs.

Dis article help you?