Operational Security for Trading VPS
Why Infrastructure Security Gets Neglected
Most retail algorithmic traders focus obsessively on strategy backtesting, overfitting, and regime detection. But when they finally deploy live, they often overlook the infrastructure that runs their strategy.
Result: a well-tuned algorithm running on a wide-open VPS, with API keys in config files, weak SSH credentials, no kill switches, and unmonitored resource exhaustion.
Two failure modes this article will not solve for you
The advice below assumes you have not yet exposed the server to the internet with weak settings. If you have already deployed with default SSH, default ports, and hardcoded secrets, treat this as a rebuild, not a patch:
- Rotate every credential that has touched that host: SSH keys, exchange API keys, database passwords, Redis passwords, MT5 passwords.
- Rebuild the VPS from a clean image. Do not try to clean an already-compromised box.
Attack escalation: how a small security oversight cascades
The sequence below is a composite of common failure modes. It is not a report of a specific incident.
-
1Password SSH on default port
Weak credentials, no rate limiting, no key requirement.
-
2Scanner detects open service
Automated scan finds port 22 responding with password auth enabled.
-
3Brute force succeeds
Weak password falls after repeated attempts from rotating addresses.
-
4API keys stolen
Exchange credentials found in an unencrypted config file.
-
5Unauthorised positions opened
Leveraged orders placed overnight, without detection or alerting.
Real risk: what happens when you are compromised
- API key theft: exchange API keys extracted from unencrypted configs; positions opened without authorisation.
- Order manipulation: man-in-the-middle intercepts API calls, modifies order size or price.
- Kill switch failure: strategy terminated maliciously; recovery takes time while the market moves against the position.
- Data exfiltration: months of backtest data stolen; proprietary work exposed.
Security Is About Blast Radius
The goal is not perfect invulnerability - that is unrealistic. The goal is to reduce blast radius.
- If a credential leaks, the attacker should not gain full system access.
- If a container fails, the rest of the infrastructure should remain isolated.
- If a strategy behaves unexpectedly, operators detect it immediately.
- If compromised, recovery should take hours, not weeks.
What experienced operators optimise for
- Fast recovery instead of perfect prevention
- Limited blast radius instead of single-point failure
- Detection latency instead of reactive troubleshooting
- Operational continuity during market stress
Scarfone, K., Jansen, W., & Tracy, M. Foundational server hardening and operational security principles.
Layer 1: Perimeter Defense
SSH Hardening: Disable Password Authentication
Password authentication
Attackers try common passwords, dictionaries, and rainbow tables against the SSH service. Weak passwords fall in minutes.
SSH key authentication
Authentication uses a key pair. The private key never leaves the client. There is no password to guess.
SSH is the primary attack surface. Default configuration allows password authentication - brute force attacks can compromise weak passwords in minutes. Disable password authentication entirely and use key-based authentication only.
ssh-keygen -t ed25519 -C "trading-vps" -f ~/.ssh/id_trading_vpsPasswordAuthentication no
PubkeyAuthentication yes
Port 22222
PermitRootLogin no
MaxAuthTries 3sudo sshd -t # validate the config before reloading
sudo systemctl restart ssh # or: sudo systemctl reload sshBefore you close your current session
- Open a second terminal and connect with the new port and key. Confirm the login works.
- Only then close your original session. If the new login fails and you have closed the old one, you may be locked out and need console access from your VPS provider.
Fail2ban: Ban Brute-Force Attackers
-
1Incoming attempts
Repeated login attempts against the SSH service from a rotating set of IPs.
-
2Detection
fail2ban reads the SSH auth log and matches failures against configured patterns.
-
3Threshold reached
Five failures within ten minutes triggers the ban rule for that IP address.
-
4Ban applied
iptables blocks traffic from the attacking IP for the configured duration.
-
5Server protected
Brute-force attempts are throttled without human intervention. Targeted attacks need other defences.
bantime = 24hjail.local if you want a longer block. fail2ban slows brute-force attacks; it does not stop targeted attacks from a determined adversary.
sudo apt-get update && sudo apt-get install -y fail2ban[DEFAULT]
bantime = 24h
findtime = 10m
maxretry = 5
[sshd]
enabled = true
port = 22222Firewall: UFW (Uncomplicated Firewall)
Order matters. If you enable UFW before allowing the new SSH port, you will lock yourself out.
sudo ufw allow from YOUR_IP to any port 22222 proto tcpsudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
sudo ufw status verboseConfirm before disconnecting
Keep your current session open. In a second terminal, connect from the allowed IP. If the connection fails, disable UFW from the session still open (sudo ufw disable) and fix the rule before proceeding.
Layer 2: Secrets & Key Hygiene
Exchange API Keys
If an exchange or broker API key is stolen and it has withdrawal permission, the loss is not bounded by your strategy. Three controls apply regardless of how carefully the VPS is hardened:
- Withdrawal permission disabled. The API key should be able to trade and read, and nothing else. Withdrawal-enabled keys turn a VPS breach into an immediate cash-out.
- IP whitelisting enabled. Bind the API key to the VPS's outbound IP. A key that works from anywhere is a key that works from anywhere.
- 2FA on the broker account itself. This protects the web login, which is a separate attack surface from the API key.
Runtime Secrets: Environment Variables
import os
api_key = os.getenv("TRADING_API_KEY")
if not api_key:
raise RuntimeError("TRADING_API_KEY is not set")The check matters. A missing variable that returns None silently will produce a live system that acts on empty credentials or fails to act when you expect it to.
MT5 Credentials
If you run an MT5 terminal on Windows, the broker login, password, and server are stored in config/*.ini and in the terminal's own data directory. These files are not encrypted. Treat the Windows host with the same standard as the VPS: full-disk encryption, automatic screen lock, and no shared-user accounts. Do not reuse the MT5 password anywhere else.
Backups
Configuration and audit logs should be backed up daily to storage outside the VPS. The backup target must be write-only from the VPS's perspective: if an attacker on the VPS can delete the backups, they are not backups. Use object storage with a scoped token and enable versioning.
Recommends environment variables over hardcoded strings, encrypted storage, and rotation policies.
Layer 3: Kill Switch & Execution
The kill switch is a single point of control that can halt trading regardless of what the strategy decides. It should be the last thing that runs, and it should be safe when it cannot reach its backend.
import os
import redis
# decode_responses=True so the value compares as a string, not bytes.
# Without this, "halt" != b"halt" and the switch silently no-ops.
r = redis.Redis(
host=os.getenv("REDIS_HOST", "127.0.0.1"),
port=int(os.getenv("REDIS_PORT", 6379)),
password=os.getenv("REDIS_PASSWORD"), # required in production
decode_responses=True,
socket_connect_timeout=1.0,
)
# ties:kill_flag holds "pause", "halt" or "kill".
# Missing key or unreachable Redis -> "run" (fail-open on read,
# fail-safe on write: the trading loop is responsible for its own
# circuit breakers if Redis is unreachable).
try:
state = r.get("ties:kill_flag") or "run"
except redis.RedisError:
state = "run"
if state == "pause":
pause_new_entries()
elif state == "halt":
close_all_positions()
elif state == "kill":
liquidate_all_positions()Three things this snippet assumes and that you should verify in your own build:
- Redis is bound to
127.0.0.1and requires a password. An unauthenticated Redis reachable from the network can be written to by anyone. - The key name matches production. If TIES uses a different key or a different set of levels, use those.
- Failure handling is explicit. Decide what your loop does when Redis is unreachable, and write that decision down.
Complete 20-Point Security Checklist
Printable PDF with scoring sheet, implementation tracker, and prioritisation guide. Audit your VPS against production-grade standards.
Request an Infrastructure Review
Scoped engineering and validation work for systematic traders and research teams. We review your SSH configuration, secrets handling, kill-switch design, and monitoring.
Complete Security Checklist
20-Point VPS Security Checklist
- SSH: disable password auth, enable keys only
- Change default SSH port
- PermitRootLogin no
- MaxAuthTries 3
- Install fail2ban
- Configure fail2ban for custom SSH port and longer bantime
- UFW: allow your SSH port before enabling the firewall
- UFW: default deny incoming, allow SSH only from your IP
- Remove hardcoded credentials from config and compose files
- Use environment variables or a secrets manager
- .env file permissions 600
- Bind Postgres and Redis to
127.0.0.1, not all interfaces - Set a Redis password; do not run unauthenticated Redis
- Exchange API keys: withdrawal permission disabled
- Exchange API keys: IP whitelisting enabled, 2FA on the account
- Prometheus metrics and Grafana alerts for anomalies
- Daily backups to write-only external storage with versioning
- Kill switch with explicit pause / halt / kill levels
- Monitor failed login attempts and kill switch state
- Incident response plan written down and rehearsed
Conclusion: Security Is Risk Management
The controls above cover the common failure modes for a single-VPS trading deployment. Most operate automatically once configured. Your strategy edge only matters if your infrastructure survives long enough to exploit it.