Trading bots need exchange API keys, and those keys often control real money. Unlike most API credentials, a leaked exchange key can be used to drain funds in minutes, either directly through withdrawals or indirectly through trades that move value to an attacker. Many reported losses from bots come down to the same few mistakes: keys with withdrawal permission, no IP restriction, keys in code repositories or logs, and nobody watching.
This guide is the checklist we apply to every key used by our trading systems. It is written for engineers running bots against centralised exchanges; specifics differ between exchanges, but the controls are similar.
1. Least privilege on the key itself
Exchanges let you choose permissions per key. Typical options: read only, spot trading, margin trading, futures trading, withdrawals, internal transfers, and sometimes "universal transfer" between account types.
- Never enable withdrawals on a trading key. If a process needs to move funds out, use a separate key on a separate, tightly controlled path with an address allowlist.
- Enable only the markets the bot trades. A spot bot does not need futures or margin permissions.
- Separate read-only keys for monitoring, dashboards and reconciliation jobs.
- One key per bot or service, never shared, so you can revoke one without stopping everything and see which system did what.
2. IP allowlists
Restrict each key to the static outbound IP addresses of the hosts that use it. Many exchanges require an IP restriction before allowing trading permissions on newer key types, and some expire unrestricted keys after a period. With an allowlist, a leaked key is useless from anywhere else.
That means your bots need stable egress IPs: an Elastic IP on a VM, a NAT gateway for a private subnet, or a dedicated egress proxy. Do not run trading on hosts with changing IPs and then widen the allowlist to compensate.
3. Sub-accounts to limit blast radius
Put each strategy or bot in its own sub-account, funded only with the capital it needs. A compromised or buggy bot can then only affect that sub-account. The main account holds reserves and is not used by any automated key.
4. Store secrets properly
- Keep keys in a secret manager (cloud provider secret manager, Vault), not in environment files committed to Git, not in container images, not in CI variables printed by debug steps.
- Grant each bot's runtime identity access only to its own secret.
- Load the secret at startup into memory; avoid writing it to disk.
- Run secret scanning in CI and pre-commit hooks for key formats used by your exchanges.
import boto3, json
def load_exchange_key(secret_id: str) -> tuple[str, str]:
raw = boto3.client("secretsmanager").get_secret_value(SecretId=secret_id)["SecretString"]
data = json.loads(raw)
return data["api_key"], data["api_secret"]
5. Asymmetric keys where available
Some exchanges support Ed25519 or RSA key pairs for API authentication: you register a public key, and the private key never leaves your system. Compared with shared HMAC secrets, the exchange never stores a secret that could sign your requests, and the private key can live in a hardware module or KMS-backed signer. Prefer them when offered.
6. Logging without leaking
Request logs are a frequent leak. Never log:
- API secrets or private keys.
- Full signed query strings or signatures (a signature plus timestamp can sometimes be replayed within the receive window).
- Full request headers, which carry the API key.
Log the endpoint, a request id, status, latency and the order's client id instead. Redact at the HTTP client layer so no developer can accidentally log too much.
7. Rotation
Rotate keys on a schedule (we use 90 days) and immediately when someone with access leaves, when a host is rebuilt from an unknown state, or when anything suspicious happens. Rotation should be routine and scripted: create the new key with the same permissions and allowlist, store it in the secret manager, roll the bot, verify, delete the old key. If rotation is painful, it will not happen.
8. Monitoring and alerts
- Alerts on API key creation, permission changes and allowlist changes in the exchange account (via email or account notifications, routed to a monitored channel).
- Alerts on unexpected trades: symbols the bot does not trade, sizes above limits, trades outside the bot's own client order id prefix.
- Alerts on login from new locations and on withdrawal address changes for the main account.
- Daily reconciliation of balances against the bot's internal ledger.
9. Incident response
Write the runbook before you need it:
- Disable the key (or delete it) in the exchange.
- Cancel open orders for the affected sub-account.
- Check recent trades and transfers for anything not initiated by the bot.
- Rotate secrets on the host and investigate how the key leaked.
- Re-enable with a new key only after the cause is understood.
Practise step 1 and 2: you want them to take less than a minute.
Common mistakes
| Mistake | Why it hurts | Do this instead |
|---|---|---|
| Withdrawal permission on trading keys | Leaked key drains funds | Trading-only keys, separate withdrawal path |
| No IP allowlist | Key usable from anywhere | Allowlist static egress IPs |
| One key for many bots | Cannot isolate or revoke cleanly | One key per bot, per sub-account |
| Keys in repos, images or logs | Most common leak path | Secret manager, scanning, redaction |
| No rotation process | Old keys live forever | Scripted rotation every 90 days |
Key takeaways
- Trading keys never get withdrawal permission.
- Restrict keys to fixed IPs and to one bot and sub-account each.
- Store keys in a secret manager and keep them out of logs.
- Prefer asymmetric key types where the exchange supports them.
- Monitor account changes and practise the revoke-and-cancel runbook.
References
- Binance API key types and security — https://developers.binance.com/docs/binance-spot-api-docs/faqs/api_key_types
- Binance Spot API, signed endpoint security — https://developers.binance.com/docs/binance-spot-api-docs/rest-api/endpoint-security-type
- OWASP Secrets Management Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
- AWS Secrets Manager — https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.