A trading bot’s API key can place and cancel orders. A dashboard key only needs to read account data, and public market data usually needs no key. Set those permissions in the exchange’s API management page, then check the key from the bot’s host before it starts.
Technical Disclaimer
These articles are software engineering references for exchange API integrations. They are not financial, investment, legal, tax, compliance, or trading advice. Use public data, demo, testnet, or paper workflows first. Keep API credentials out of frontend code and disable withdrawal permissions for automation keys.
Why Exchange API Keys Need Their Own Rules
If an exchange key leaks in a commit, a log or a chat, anyone who gets it can attempt the actions its permissions allow. Bind each key to the bot’s outbound IP addresses and keep withdrawals and transfers disabled.
The examples use the open-source Siebly SDKs for Node.js.
1. Grant the Minimum Permissions
Grant only the permissions the service needs. NIST calls this least privilege. Check the exchange settings for each permission in the table.
| Job | Permission it needs | Permission it must not have |
|---|---|---|
| Public prices, order books, candles | No key at all | Any |
| Dashboard, reconciliation, tax export | Read only | Trade, transfer, withdraw |
| Order placement and cancellation | Read and trade on the products it uses | Transfer, withdraw |
| Moving funds | A separate, human-controlled process | Should not be an automation key |
Never enable withdrawal permission on a key used by a bot, a script or an AI agent. If a process really needs to move funds, it belongs on a separate key, on a separate host, with its own approval step.
- Binance lets you scope keys to types of endpoint and gives the example of a
TRADEkey for trading alongside a separateUSER_DATAkey for monitoring. By default, a new key cannot trade until you enable it. (Binance Spot API: request security) - OKX defines three permissions, Read, Trade and Withdraw, and any key can carry one or more of them. (OKX API v5 documentation)
- Kraken lists each permission separately, including Withdraw Funds, and notes that a trading client would almost certainly not require it. (Kraken: how to create an API key, Kraken API key permissions)
- Bybit exposes read-only versus read-write keys and per-product permission groups, and its key-info endpoint reports them. (Bybit: get API key information)
- Gate lets you create multiple keys, each with its own set of permissions. (Gate API v4)
- Coinbase offers permission restrictions when you create a CDP API key. (Coinbase: CDP API keys)
- KuCoin and Bitget both ask you to choose permissions and set an API passphrase at creation. (KuCoin: creating an API, Bitget: API creation guide)
Also limit the products. A spot-only bot does not need futures, margin or options permissions.
Check the key’s permissions at start-up
Check the key from the host that will run the bot. Access can change after deployment if someone edits the key in the exchange dashboard or deploys the wrong credential.
The binance SDK calls Binance’s key-permissions endpoint via getApiKeyPermissions(). The example requires IP restriction and checks three withdrawal and transfer flags.
binance-key-guard.mjs
import { MainClient } from 'binance';
const api_key = process.env.BINANCE_API_KEY;
const api_secret = process.env.BINANCE_API_SECRET;
if (!api_key || !api_secret) throw new Error('Set BINANCE_API_KEY and BINANCE_API_SECRET');
const client = new MainClient({ api_key, api_secret });
const key = await client.getApiKeyPermissions().catch(() => {
throw new Error('Binance key permissions could not be verified');
});
const problems = [];
if (key?.ipRestrict !== true) problems.push('IP restriction was not confirmed');
if (key?.enableWithdrawals !== false) problems.push('withdrawals were not confirmed off');
if (key?.enableInternalTransfer !== false) problems.push('internal transfer was not confirmed off');
if (key?.permitsUniversalTransfer !== false) problems.push('universal transfer was not confirmed off');
if (problems.length > 0) {
throw new Error(`Refusing to start: ${problems.join('; ')}`);
}
console.log('Binance IP, withdrawal and transfer checks passed.');
The bybit-api SDK calls Bybit’s key-info endpoint via getQueryApiKey(). Bybit documents ips as the bound IP list and shows a response with specific addresses. The docs leave the unrestricted response unspecified. This example requires at least one concrete IP address and rejects the entire list if any entry is a wildcard or invalid. It also requires an empty Wallet permission group, which covers withdrawal and transfer grants.
bybit-key-guard.mjs
import { isIP } from 'node:net';
import { RestClientV5 } from 'bybit-api';
const key = process.env.BYBIT_API_KEY;
const secret = process.env.BYBIT_API_SECRET;
if (!key || !secret) throw new Error('Set BYBIT_API_KEY and BYBIT_API_SECRET');
const client = new RestClientV5({ key, secret });
const response = await client.getQueryApiKey().catch(() => {
throw new Error('Bybit key permissions could not be verified');
});
if (response?.retCode !== 0 || !response.result) {
throw new Error('Bybit key permissions could not be verified');
}
const { ips, permissions } = response.result;
const ipBound = Array.isArray(ips) && ips.length > 0
&& ips.every((ip) => typeof ip === 'string' && isIP(ip) !== 0);
const wallet = permissions?.Wallet;
if (!ipBound) {
throw new Error('Refusing to start: Bybit did not report a concrete IP allowlist');
}
if (!Array.isArray(wallet) || wallet.length !== 0) {
throw new Error('Refusing to start: Bybit did not confirm an empty Wallet permission group');
}
console.log('Bybit IP and Wallet checks passed.');
Both examples make a signed read. Check the exact egress IPs and product permissions in the exchange dashboard as well.
2. Use Strict IP Whitelists
An IP whitelist (also called an allowlist) makes a leaked key much less useful, because requests from any other address are rejected. Kraken’s documentation describes IP whitelisting as the single measure that prevents almost all key misuse even if the key is leaked. (Kraken API key permissions)
Exchange rules for keys without an allowlist vary.
- Binance limits system-generated HMAC keys without IP restrictions to read-only access under its default security controls. Binance’s security guide also says keys without an allowlist can be deleted after 30 days of inactivity. Check the rules for your key type in API Management. (Binance API key FAQ, Binance API key security guide)
- OKX lets each key bind up to 20 IP addresses. Live keys with Trade or Withdraw permissions and no bound IP expire after 14 days of inactivity. (OKX API v5 documentation)
- KuCoin: trading-enabled keys that are not linked to an IP address are deleted or have trade permission disabled after 30 days of inactivity. (KuCoin: creating an API)
- Bybit documents
expiredAtanddeadlineDayfor keys without a bound IP or after an account password change. (Bybit: get API key information) - Coinbase recommends allowlisting the IP addresses permitted to use each key. (Coinbase App API key authentication)
- Kraken offers IP Address Restriction per key. Bitget asks you to link an IP address during key creation. (Kraken, Bitget)
Get a static egress IP
Use a stable outbound address. Home broadband, serverless functions and autoscaled containers can change the address the exchange sees.
- A virtual machine with a reserved static IP.
- A NAT gateway in front of private workloads.
- A static egress proxy service.
For the proxy route, QuotaGuard publishes a worked example that sends both REST and WebSocket traffic from @siebly/hyperliquid-api through its static IPs and prints the egress IP so you can confirm it. (QuotaGuard static examples: Hyperliquid SDK) Its README makes an important point: check the egress IP the exchange actually sees, rather than trusting a successful response, because a misconfigured agent can silently fall back to the server’s own address.
Siebly’s guide to HTTP and SOCKS proxies with Siebly SDKs and each SDK’s proxy guide, such as the Binance proxies guide, cover the constructor options. Remember that proxy credentials are secrets too.
3. One Key per Bot, per Environment
Use a separate key for each program and each environment. This narrows the blast radius, makes the exchange’s activity history easier to attribute, and lets you revoke one key without stopping everything else. Binance’s own documentation suggests separate keys for trading and for monitoring, and Kraken recommends separate keys per purpose so that “if one is compromised, the blast radius is contained”. (Binance, Kraken)
Sub-accounts
Where the exchange supports sub-accounts, give each bot its own sub-account and only the balance it needs. Create the key under that sub-account and keep transfer permissions off to limit what the key can reach. OKX documents endpoints to create, query, reset and delete sub-account keys. (OKX API v5 documentation)
Testnet and demo keys
Develop against testnet or demo environments first, with keys created there. Bybit, for example, has a separate testnet key management page, Gate publishes a separate testnet base URL, and OKX has demo trading. (Bybit: create an API key, Gate API v4)
Keys are generally issued per environment and rejected elsewhere, which is a useful safety property: a development machine holding only testnet keys cannot touch real funds. The SDKs make the environment explicit:
environments.mjs
import { RestClientV5 } from 'bybit-api';
import { RestClient as OkxRestClient } from 'okx-api';
const bybit = new RestClientV5({
key: process.env.BYBIT_TESTNET_KEY,
secret: process.env.BYBIT_TESTNET_SECRET,
testnet: true,
});
const okx = new OkxRestClient({
apiKey: process.env.OKX_DEMO_API_KEY,
apiSecret: process.env.OKX_DEMO_API_SECRET,
apiPass: process.env.OKX_DEMO_API_PASSPHRASE,
demoTrading: true,
});
Name variables by environment, as above, so that a production secret is never loaded by accident. Siebly’s guide to testnet, demo and local simulation in Node.js and the Binance testing environments guide go further.
4. Store Secrets Outside the Code
The OWASP Secrets Management Cheat Sheet is the best single reference here. Its main recommendations are to centralise secrets, apply least privilege to who and what can read them, audit access, and automate rotation.
In order of preference for a server-side bot:
- A secret manager (a cloud provider’s secrets service, HashiCorp Vault or similar), with access limited to the identity the bot runs as.
- Environment variables injected at deploy time by your orchestrator or platform. The Twelve-Factor App recommends strict separation of config from code. Note that the OWASP cheat sheet cautions that environment variables are generally accessible to all processes and may appear in logs or system dumps, so treat them as a fallback rather than a vault.
- A local
.envfile for development only, never committed. Node.js can load it with the built-in--env-fileflag.
Never put exchange keys in:
- Source files, config files committed to Git, or Docker
ENV/ARGinstructions (OWASP calls this out specifically). - Browser, mobile or desktop app bundles. Anything shipped to a client can be extracted.
- Shared drives, tickets, chat messages or screenshots.
Whatever the storage, read the key once at start-up and fail fast if it is missing:
load-keys.mjs
import { RestClient } from 'okx-api';
function requireEnv(name) {
const value = process.env[name];
if (!value) throw new Error(`Missing required environment variable ${name}`);
return value;
}
export const okx = new RestClient({
apiKey: requireEnv('OKX_API_KEY'),
apiSecret: requireEnv('OKX_API_SECRET'),
apiPass: requireEnv('OKX_API_PASSPHRASE'),
});
The error names the variable, never its value.
Keep keys out of Git
Add local secret files to .gitignore before you create them:
.gitignore
.env
.env.*
!.env.example
*.pem
*.key
Commit a .env.example with variable names and empty values so others know what to set.
Then add automated checks, because .gitignore only helps with files you remembered:
- Pre-commit scanning with Gitleaks, which detects secrets such as passwords, API keys and tokens in Git repositories and files (for example
gitleaks git -v), or AWS Labs’ git-secrets, which prevents you from committing passwords and other sensitive information. - GitHub secret scanning, which scans the entire Git history on all branches for hardcoded credentials. (About secret scanning)
- GitHub push protection, which blocks pushes that contain secrets before they reach the repository. Push protection for users is enabled by default for pushes to public repositories; push protection at repository level must be enabled by an administrator. (About push protection)
Check GitHub’s supported secret scanning patterns for the providers you use. Where your exchange’s key format is not covered, add a custom pattern in Gitleaks or in GitHub so that scanning does not give false comfort.
5. Prefer Asymmetric Key Types Where Available
Most exchange keys are HMAC: the exchange generates a shared secret, and both sides hold it. Asymmetric keys change that. You generate a key pair, register only the public key with the exchange, and the private key never leaves your systems.
- Binance supports Ed25519, HMAC and RSA keys, and recommends Ed25519 for the best performance and security. Its documentation notes that HMAC requires a shared secret, which is less secure than the asymmetric cryptography used by Ed25519 or RSA. (Binance: API key types)
- Bybit supports self-generated RSA keys, where you provide only the public key and Bybit never holds your private key. (Bybit V5 integration guide)
- Coinbase CDP API keys offer a choice of signature algorithm, with Ed25519 recommended in the general CDP key guide. Some Coinbase products require ECDSA instead, so check the page for the product you integrate. (CDP API keys, Coinbase App API key authentication)
The Siebly SDKs accept these key types through the normal secret option. In the binance SDK, passing a private key as api_secret automatically switches to RSA or Ed25519 signing. In coinbase-api, the CDP key name goes in apiKey and the private key in apiSecret:
asymmetric-keys.mjs
import { MainClient } from 'binance';
import { CBAdvancedTradeClient } from 'coinbase-api';
// Binance Ed25519: the API key from Binance, plus your PEM private key.
const binance = new MainClient({
api_key: process.env.BINANCE_ED25519_API_KEY,
api_secret: process.env.BINANCE_ED25519_PRIVATE_KEY_PEM,
});
// Coinbase CDP key: key name and private key from your secret store.
const coinbase = new CBAdvancedTradeClient({
apiKey: process.env.COINBASE_CDP_KEY_NAME,
apiSecret: process.env.COINBASE_CDP_PRIVATE_KEY,
});
An asymmetric private key is still a secret and needs the same storage rules. Preserve real line breaks in PEM content: an environment variable containing literal \n characters is a different string from a multi-line key unless your loader converts it. The per-SDK authentication guides on the docs portal cover the details: Binance, Bybit, Coinbase.
6. Use a Dedicated Hyperliquid API Wallet
Hyperliquid has no API key in the exchange sense. Requests are signed with a wallet private key, which makes the choice of key even more important. Hyperliquid’s answer is the API wallet, also called an agent wallet: a master account approves a separate wallet to sign on its behalf. (Hyperliquid: nonces and API wallets)
Practical rules from the Hyperliquid documentation:
- API wallets are only used to sign. To query account data, pass the master or sub-account address.
- Use a separate API wallet per trading process, and separate API wallets for separate sub-accounts, because nonces are tracked per signer.
- Do not reuse API wallet addresses after deregistration. Once an agent is deregistered or expires, its nonce state may be pruned, and previously signed actions could then be replayed. Generate a new one.
Keep your main wallet key off the server entirely. With @siebly/hyperliquid-api, the API wallet key goes in privateKey and the master address in accountAddress:
hyperliquid-api-wallet.mjs
import { RestClient } from '@siebly/hyperliquid-api';
const apiWalletPrivateKey = process.env.HYPERLIQUID_API_WALLET_KEY;
const masterAddress = process.env.HYPERLIQUID_MASTER_ADDRESS;
if (!apiWalletPrivateKey || !masterAddress) {
throw new Error('Set the API wallet key and master address before starting.');
}
const client = new RestClient({
privateKey: apiWalletPrivateKey,
accountAddress: masterAddress,
});
The SDK also accepts a signer object that exposes signTypedData, so signing can be delegated to a component that holds the key separately. See the Hyperliquid authentication guide and the Hyperliquid tutorial.
7. Rotate and Expire Keys
Rotation limits how long a stolen key stays useful. NIST SP 800-57 Part 1, Recommendation for Key Management, is the reference standard for managing keying material over its life cycle. CIS Controls 5 (Account Management) and 6 (Access Control Management) cover managing, and revoking, credentials for service accounts as well as people.
For exchange keys, that translates to:
- Set an expiry where the exchange supports it. Kraken offers Key Expiration, for example a key that is only valid for one week. (Kraken)
- Rotate on a schedule you can actually keep, and whenever someone with access leaves or a machine is retired.
- Verify the new key before revoking the old one. Deploy the replacement, run the start-up checks and confirm the running bot uses it.
- Delete unused keys. Review the exchange’s API management page regularly and remove anything you cannot attribute to a running system.
The OWASP cheat sheet’s guidance on rotation and dynamic secrets is a good model even where the exchange cannot issue short-lived credentials itself.
8. Keep Secrets Out of Logs and Errors
Logs are copied, shipped, indexed and shared in support threads. The OWASP Logging Cheat Sheet lists access tokens, authentication passwords, and encryption keys and other primary secrets among the data that should usually not be recorded directly in logs, but removed, masked, sanitised, hashed or encrypted instead.
For exchange integrations, watch for:
- Logging a whole client options object, request config or HTTP headers, which may contain the key or signature.
- Error handlers that serialise the full request.
- Debug output of environment variables.
- Proxy URLs that embed a username and password.
A small redaction helper at the logging boundary helps:
redact.mjs
const SENSITIVE = /key|secret|pass|signature|token|authorization/i;
export function redact(value) {
if (Array.isArray(value)) return value.map(redact);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, SENSITIVE.test(k) ? '[redacted]' : redact(v)]),
);
}
return value;
}
Keep raw requests and responses out of logs. For support, share the exchange error code and a sanitised message. Strip headers, signed URLs and credentials from any diagnostic output.
9. Coding Agents, AI Assistants and MCP Servers
Coding agents and AI assistants are now part of many trading-system workflows. They add new places a key can leak and new ways a key can be misused. The OWASP Top 10 for LLM Applications lists Sensitive Information Disclosure, including security credentials, as LLM02:2025, and Excessive Agency as LLM06:2025, which includes giving an extension more permissions on downstream systems than its task needs.
Practical rules:
- Never paste a key or secret into a prompt, chat window or issue description. Treat anything you send to a hosted assistant as having left your control.
- Keep secrets outside the agent’s workspace. Inject the credentials only into the process that runs the bot. A
.gitignoreentry only affects Git. - Run the agent’s tests against public data or a sandbox. If it needs authenticated production data, provide a dedicated read-only path with access to only the data the task needs.
- Review generated code for secret handling before running it: hardcoded placeholders that get replaced with real keys, logging of request config, or keys sent to a frontend.
- For MCP servers that call exchanges, give each server its own narrowly scoped, IP-restricted key, and keep that key server-side. The MCP specification’s security best practices describe “token passthrough” as an anti-pattern and recommend minimal scopes and least privilege.
Siebly publishes agent skills that give coding agents current SDK references; the guide to using Siebly skills with a coding agent suggests validating a public-data task first, which needs no credentials at all.
10. If a Key Leaks: Response Checklist
Assume a key is compromised as soon as it appears anywhere it should not: a commit, a log, a screenshot, a prompt. The OWASP cheat sheet’s incident response section lists revocation, rotation and deletion as the containment steps, and Binance’s documentation says to revoke all keys and contact support if you notice unusual activity. (OWASP, Binance)
- Revoke or delete the key at the exchange immediately. Do this before cleaning up Git history; history rewriting does not un-leak a key, and secret scanning shows how long history persists.
- Stop the affected bot so it does not keep retrying with a dead key or acting on stale state.
- Review account activity: open orders, trades, transfers and API key changes since the earliest possible exposure. Cancel anything you did not place.
- Check other keys and the account itself. If the leak came from a compromised machine, assume every secret on it is exposed, and review the exchange account’s login security.
- Create a replacement key with the same minimum permissions and IP restrictions, and deploy it.
- Remove the secret from where it leaked: the file, the log store, the ticket. Rewrite Git history only after revocation.
- Contact the exchange through its official support channel if you see activity you did not authorise.
- Write down what happened and fix the cause, such as a missing
.gitignoreentry, a verbose logger or a missing pre-commit hook.
Printable API Key Security Checklist
Creating a key
- [ ] The key serves one bot or service in one environment.
- [ ] Permissions are the minimum for the job: read only, or read and trade on the products used.
- [ ] Withdrawal and transfer permissions are off.
- [ ] The key is bound to the static egress IP addresses of the hosts that use it.
- [ ] An expiry is set where the exchange supports it.
- [ ] An asymmetric key type (Ed25519 or RSA) is used where the exchange supports it.
- [ ] The key lives in a sub-account with only the balance it needs, where supported.
Storing and using a key
- [ ] The secret is in a secret manager or injected at deploy time, never in source code.
- [ ]
.envand key files are in.gitignore, and only.env.exampleis committed. - [ ] Gitleaks or git-secrets runs before commits, and GitHub secret scanning and push protection are on.
- [ ] Secrets never reach browsers, mobile apps or other client bundles.
- [ ] Logs and error reports redact keys, signatures and authorisation headers.
- [ ] The program checks its own key restrictions at start-up where the exchange allows it.
- [ ] Development and coding agents use testnet, demo or read-only keys.
- [ ] Keys are never pasted into AI prompts, chats or issues.
Over time
- [ ] Keys are rotated on a schedule, and on staff or machine changes.
- [ ] Unused keys are deleted after regular review of the API management page.
- [ ] A written leak response plan exists, starting with “revoke the key”.
Frequently Asked Questions
Should a trading bot’s API key have withdrawal permission?
No. A bot needs to read balances and place or cancel orders. Withdrawal permission turns a leaked key into a direct route out of the account. If you must automate fund movements, use a separate key, a separate host and a human approval step.
What is an IP whitelist on an exchange API key?
It is a list of IP addresses allowed to use the key. Requests from any other address are rejected, so a leaked key is far less useful. OKX and KuCoin also expire or restrict trading keys that are left unbound and inactive.
Are environment variables safe for API keys?
They are better than hardcoding and are common for server-side bots, but they are not a vault. OWASP notes that environment variables are generally visible to all processes and can appear in logs or dumps, so prefer a secret manager in production and inject only the variables the bot needs.
Is Ed25519 better than HMAC for exchange API keys?
Binance recommends Ed25519 for the best performance and security among its key types. The main benefit of asymmetric keys is that you only give the exchange your public key, so the exchange never holds the private signing key. Support varies by exchange and product.
How often should I rotate exchange API keys?
There is no single exchange-wide rule. Rotate on a schedule you can maintain, whenever access changes, and immediately after any suspected exposure. Use the exchange’s expiry setting where it exists, such as Kraken’s Key Expiration.
Can I give an AI coding assistant my exchange API key?
Keep exchange credentials out of prompts and chats. Let the assistant write code that reads credentials at runtime, then run it yourself with demo, testnet or read-only keys as appropriate.
What should I do if I committed an API key to GitHub?
Revoke the key at the exchange first, then review account activity, create a replacement, and only then clean up the repository. Deleting the commit does not make the key safe again.
On Hyperliquid, should my bot use my main wallet’s private key?
No. Approve an API wallet (agent wallet) for the bot and keep the main wallet key off the server. Use one API wallet per process and generate a new one rather than reusing a deregistered address.
Related articles
- Testnet, Demo, and Local Simulation in Node.js
- HTTP and SOCKS Proxies with Siebly SDKs
- Diagnosing Bybit Authentication Errors in Node.js
- Using Siebly Skills with a Coding Agent
- Pre-Trade Checks and Kill Switches for Trading Bots
Related Siebly Resources
- SDK tutorials: Binance, Bybit, OKX, Coinbase, Kraken, KuCoin, Gate, Bitget, Hyperliquid
- Authentication guides on the Siebly docs portal: Binance, Bybit, OKX, Coinbase, Kraken, KuCoin, Gate, Bitget, Hyperliquid
- Binance production usage guide
