Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Trading and crypto

Run a crypto trading bot safely: keys, limits, failures

How a crypto trading bot talks to an exchange, how to lock down its API key, why fees and rate limits matter, and how to keep it running on a server.

CloudSat teamNovember 18, 20268 min read
Abstract illustration of a small robot arm placing orders on a glowing order book beside a padlocked key
On this pageWhat a bot is made of

A trading bot is a program that reads market data, applies fixed rules and sends orders through an exchange's API. The rules get the attention, yet many bot failures have nothing to do with them: a leaked key, a clock that drifted, a rate-limit ban, a crash halfway through a partial fill. This guide covers how a bot is put together, the ways to run one, and the server habits that keep the key and the account safe.

What a bot is made of

Every bot, from a short script to a full framework, has the same parts, and each one fails in its own way.

Part Job What goes wrong without it
Market data feed Streams trades, order book changes or candles, usually over WebSocket, with REST calls for snapshots Decisions on stale prices after a silent disconnect
Signal logic Turns data into "buy", "sell" or "do nothing" Nothing by itself; this is the part people write first
Order manager Places, amends and cancels orders, and tracks each one until it is filled or gone Duplicate orders, orphaned orders, mishandled partial fills
Risk checks Caps order size, position size and daily loss, and halts the bot at a cap One bad loop can trade the whole balance
State store Records open orders and positions on disk A restart forgets what the bot owns
Logs and alerts Records what happened and wakes you when it stops You learn about problems from your balance

On every start, a well-behaved bot asks the exchange for its open orders and balances and reconciles them with its own records before it acts. Skipping that step is how a restart doubles a position.

Three ways to run one

Route Who holds the API key How far you can customize Who keeps it running
Bots built into an exchange (grid, recurring buys, rebalancing) No key leaves the exchange The exchange's settings only The exchange
Hosted bot platforms The platform, with trade rights on your account Templates and parameters The platform
Self-hosted: open source or your own code You, on your own server Anything you can write You

Three self-hosted projects come up often. Freqtrade is a Python bot under GPL-3.0 with backtesting, a dry-run mode on simulated funds, parameter optimization and control through Telegram or a web UI; its documentation asks for at least 2 GB of RAM, 1 GB of disk and 2 vCPUs. Hummingbot is an Apache-2.0 Python framework from the Hummingbot Foundation, best known for market making, with a Gateway component for decentralized exchanges. CCXT is not a bot but an MIT-licensed library that wraps the APIs of more than 100 exchanges behind one interface, in Python, JavaScript, TypeScript, PHP, C#, Go, Java and Rust, which makes it a common base for custom bots.

None of these routes makes a strategy profitable. What separates them is who keeps the API key and who is on call when something fails.

Lock down the API key

An exchange API key is a password with spending power. Four rules cover most of the risk:

  1. Grant the minimum. A trading bot reads balances and places orders. It never needs withdrawal rights, so leave that permission off.
  2. Pin the key to one address. Restrict it to your server's static IPv4. A stolen key that only works from your server is of little use to a thief.
  3. One key per bot. Revoking one bot's key should not stop the others, and the exchange's API history then shows which bot did what.
  4. Keep it out of code and images. Never commit keys to Git or bake them into a container image. Store them in a root-only file and let the service manager pass them in.

Some exchanges enforce the first two. Binance is a clear example: from January 30, 2023, its system-generated HMAC keys without an IP restriction can only read, and withdrawal permission on any key requires an IP allowlist. Binance also accepts self-generated Ed25519 or RSA keys, where you register only the public half and the private key never leaves your machine; its API documentation recommends Ed25519.

On a Linux server, the pattern looks like this:

sudo useradd --system --home-dir /opt/bot --shell /usr/sbin/nologin bot
sudo install -d -o bot -g bot /opt/bot/state
sudo install -d -m 755 /etc/bot
sudo install -m 600 /dev/null /etc/bot/main.env
sudoedit /etc/bot/main.env      # EXCHANGE_KEY=... and EXCHANGE_SECRET=...
# /etc/systemd/system/bot.service
[Unit]
Description=Trading bot
Wants=network-online.target
After=network-online.target

[Service]
User=bot
WorkingDirectory=/opt/bot
EnvironmentFile=/etc/bot/main.env
ExecStart=/opt/bot/.venv/bin/python run.py
Restart=on-failure
RestartSec=10
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/bot/state

[Install]
WantedBy=multi-user.target

systemd reads the root-only env file and passes the variables to the bot, which runs as an unprivileged user. ProtectSystem=strict leaves only the state folder writable.

Fees and rate limits set the boundaries

Fees set the smallest price move a trade must capture to break even. A round trip pays two fees plus the spread. At a hypothetical taker fee of 0.10% per side, buying and selling costs 0.20% of the position before the spread, so a bot aiming for 0.15% moves loses money on every trade it "wins". Maker and taker rates differ and tiers change with volume, so check the current schedule. Lower fees do not create an edge; they only move the break-even line.

Rate limits set how often the bot may ask. At Binance, request limits are counted per IP address, not per key. Going over returns HTTP 429, and an address that keeps sending after a 429 gets an HTTP 418 ban that scales from 2 minutes up to 3 days for repeat offenders. Every response carries an X-MBX-USED-WEIGHT-... header with the weight used so far, and 429 and 418 responses include Retry-After. Three consequences:

  • Subscribe to WebSocket streams for prices instead of polling REST endpoints in a loop.
  • Read the used-weight header and slow down before the limit, not after.
  • Several bots on one server share one IP address, and therefore one budget.

Clocks, disconnects and other quiet failures

Signed requests carry a timestamp. Binance rejects a request that arrives outside its recvWindow, which defaults to 5,000 ms and can be raised to 60,000 ms, though the documentation recommends 5,000 or less. A clock that drifts a few seconds turns every order into an error, so confirm time sync is on:

timedatectl status        # expect "System clock synchronized: yes"

Other failures to plan for:

  • Dropped streams. WebSocket connections close for maintenance, network blips or by design. The bot must reconnect, resubscribe, fetch a fresh snapshot and place no new orders while its data is stale.
  • Rejected orders. Each market has minimum sizes, price increments and order values. Read them from the exchange's market info endpoint rather than hard-coding them.
  • Partial fills. A limit order can fill in pieces over minutes. Track the filled amount rather than assuming all or nothing.
  • Maintenance windows. Exchanges pause trading or APIs for upgrades. Treat an unreachable API as "do nothing", never as "retry at full speed".

Keep it running and watched

Run the bot under systemd or Docker with automatic restarts, cap the logs and keep the operating system patched. A process marked "running" is not proof of a healthy bot, so have the bot ping a push monitor such as Uptime Kuma or Healthchecks from inside its main loop, and alert when the pings stop.

A crypto trading bot server on CloudSat has a dedicated IPv4 for the exchange allowlist and bills by the hour, so a week of testnet runs costs a week rather than a month. Close every inbound port except SSH with a cloud firewall, since the bot opens its own outbound connections and needs nothing else.

Test before real funds. Binance's Spot Test Network at testnet.binance.vision takes a GitHub login, hands out virtual balances and is reset about once a month. Freqtrade's dry-run mode runs the whole bot against live prices with simulated money. Neither reproduces real fills or slippage, so treat the results as a test of the code, not of the strategy (what simulations leave out).

Red flags when someone sells you a bot

  • A promise of returns, "guaranteed" or otherwise. Nobody can promise them.
  • A request for a key with withdrawal permission, or for your exchange password.
  • A closed-source program that needs your keys, with screenshots of profits as the only evidence.

FAQ

Does a trading bot need a VPS?

It needs a machine that stays on and keeps one stable address for the key allowlist. A home PC works until it sleeps, reboots for updates or gets a new IP from the ISP.

How many bots can share one server?

As many as CPU, memory and the exchange's limits allow. Per-IP limits are shared by every bot on that address, so several busy bots may need separate servers or a deliberate split of the request budget.

What happens to open orders if the bot crashes?

They stay on the exchange. That is why the bot must reconcile at startup: load its saved state, ask the exchange for open orders and balances, and resolve any difference before placing anything new. Protective stop orders placed on the exchange keep working while the bot is down.

Does a clean testnet run mean the bot works?

It means the code ran without errors. Testnet order books are thin and artificial, so fills and slippage there say little about live markets.

Trading involves risk of loss. Nothing in this article is financial advice.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.