# API key security for trading bots: permissions, storage

URL: https://fincodelabs.com/en/blog/api-key-security-trading-bots · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Exchange APIs · Published: 2026-10-24 · Updated: 2026-11-05

API key security for trading bots: trade-only permissions, no withdrawals, IP allowlists, one key per bot, secret storage, rotation, safe logs, leak response.

**Short answer:** **API key security for trading bots** comes down to limiting what a stolen key could do and making theft harder. Give each bot its own key with trading permission only and never withdrawal rights, restrict it to your server's IP addresses, keep the secret in a secrets manager rather than in code, rotate and revoke keys deliberately, and make sure secrets never reach logs. Where an exchange offers asymmetric keys such as Ed25519, the signing key never leaves your side.

An exchange API key is a bearer credential for your money. Kraken's documentation warns that a compromised key with withdrawal rights is a direct financial risk. A key that can only trade is less dangerous but not harmless, since an attacker can still place loss-making orders.

This guide collects the controls that matter, drawing on the official Binance, Kraken, Coinbase and Bitget documentation and the OWASP Secrets Management Cheat Sheet as of October 2026. Menu names and rules change, so check the exchange's current documentation before relying on any single setting.

## Which API key permissions does a trading bot need?

Grant the minimum a component needs and nothing more. Public market data needs no key at all. A spot trading bot needs to read balances and orders and to place and cancel orders; it never needs withdrawals or transfers.

**Permissions by use case on official pages, read in October and on 4 November 2026**

| Use case | Binance | Kraken | Coinbase | Bitget |
| --- | --- | --- | --- | --- |
| Dashboard, monitoring (read) | `enableReading` | Query Funds; Query Open Orders & Trades; Query Closed Orders & Trades | `can_view` | Read-only key; read permission |
| Spot trading bot (read and trade) | `enableReading` plus `enableSpotAndMarginTrading`; futures use `enableFutures` | Query Funds; Query Open Orders & Trades; Create & Modify Orders; Cancel/Close Orders; Access WebSocket API for private streams | `can_view` plus `can_trade` | Read/write key; trade permission |
| Funds can leave: keep off | `enableWithdrawals`, `enableInternalTransfer`, `permitsUniversalTransfer` | Withdraw Funds | `can_transfer` | Transfer; withdraw (whitelisted IP only) |

Binance keys cannot trade until trading is enabled, and its documentation suggests splitting roles, for example one key with trade permission and another that only monitors order status. A read only API key on Binance has only `enableReading` set, which is enough for reporting tools such as the [crypto portfolio risk dashboard](https://fincodelabs.com/en/projects/crypto-portfolio-risk-dashboard) scenario. A [read-only portfolio tracker](https://fincodelabs.com/en/blog/crypto-portfolio-tracker-api) works the same way.

Names change. Where to create each key is covered in the [exchange API key guide](https://fincodelabs.com/en/blog/exchange-api-key-how-to).

### An API key is not a crypto wallet key

An exchange API key can be limited by permission and revoked. A wallet's seed phrase controls everything in the wallet, and Coinbase warns that anyone holding it can steal the contents. A bot trading through an exchange API key has no need for one, so a bot setup that asks for a seed phrase is a reason to stop.

## Trading bot withdrawal permission: keep it off

A trading key that can withdraw turns a leak into a theft, so leave withdrawal and transfer rights disabled and make the bot check this itself. Binance requires an IP restriction before withdrawal permission can be enabled, but that is a floor, not a reason to enable it. On Binance a bot can read its own key's settings from `GET /sapi/v1/account/apiRestrictions` (weight 1), which returns flags such as `ipRestrict`, `enableWithdrawals`, `enableInternalTransfer` and `permitsUniversalTransfer`. This start-up guard refuses to run if the key could move funds or is usable from any IP; it is tested here on the sample response from Binance's documentation, because `/sapi` endpoints do not exist on the Spot Testnet:

```python
def key_problems(r):
    """Return reasons to refuse start-up, given GET /sapi/v1/account/apiRestrictions."""
    problems = []
    if r.get("enableWithdrawals"):
        problems.append("withdrawals enabled")
    if r.get("enableInternalTransfer") or r.get("permitsUniversalTransfer"):
        problems.append("transfers enabled")
    if not r.get("ipRestrict"):
        problems.append("no IP restriction")
    return problems

# Sample response from Binance's documentation (abridged)
sample = {"ipRestrict": False, "enableReading": True, "enableWithdrawals": False,
          "enableInternalTransfer": True, "permitsUniversalTransfer": True,
          "enableSpotAndMarginTrading": False}
problems = key_problems(sample)
if problems:
    raise SystemExit("refusing to start: " + ", ".join(problems))
```

On that sample it exits with `refusing to start: transfers enabled, no IP restriction`. Treat any developer or service that asks for a withdrawal-enabled key as a red flag, a point also made in [trading bot cost drivers](https://fincodelabs.com/en/blog/trading-bot-cost).

## IP whitelist for API keys and webhook endpoints

An IP allowlist makes a leaked key useless from anywhere else, and Kraken calls it the single measure that prevents almost all key misuse. Binance goes further: since 30 January 2023, system-generated HMAC keys without an IP restriction can by default only be set to read, and the restriction is entered as IPv4 addresses. Coinbase recommends, but does not require, an IP allowlist on its API keys. To use allowlisting, run the bot from a fixed outbound address, such as a cloud server with a static IP, and list every host that signs requests.

Inbound endpoints need protection too. If a TradingView alert triggers orders, the webhook is effectively a trading credential. TradingView's Help Center lists the four IP addresses its webhooks come from, accepts only ports 80 and 443, cancels requests that take longer than three seconds, and advises against putting credentials in the message. Allowlist those addresses, require a secret in the payload, and validate every field before an order is built, as described in the [TradingView webhook bot](https://fincodelabs.com/en/blog/tradingview-webhook-bot) guide.

A direct connection through TradingView's own panel is a different setup, because the key leaves your server. Bitget's guide, dated 27 March 2026, says a Bitget API key for TradingView does not support single-IP binding, although a whitelist can be configured in API management. Any key held outside your own systems deserves the narrowest permissions and no withdrawal rights.

## Separate keys per bot, environment and sub-account

One key per bot, process and environment limits the damage from any single leak and makes revocation surgical. Kraken recommends separate keys per purpose, and on Kraken sharing one key across processes also causes out-of-order nonce errors. Separate keys give you clean audit trails, since every order maps to one system.

- **Development**: use testnet keys only; production keys should never sit on developer laptops.
- **Isolation**: Kraken sub-accounts have their own balances and their own API keys, which caps the funds any one strategy can reach.
- **Expiry**: Kraken's key settings include optional key expiration and IP whitelisting; use them for temporary access.

## How to store API keys securely

Keep secrets out of code and images, and prefer a managed secret store over environment variables in production.

**Storage options compared**

| Option | Assessment |
| --- | --- |
| Hard-coded or committed to git | Never. Kraken says never to embed keys in source code. |
| Environment variables, .env files | Common and better than code, but OWASP notes they are generally accessible to all processes and may end up in logs or system dumps. |
| Secrets manager (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, HashiCorp Vault) | Access control per secret, audit logs and rotation support; OWASP recommends a designated solution in any environment. |
| KMS or HSM | Encryption keys never leave the service or hardware module; worth considering for high-value accounts. |

Key type matters as well. Binance marks HMAC keys as deprecated and recommends Ed25519, where you generate the key pair and upload only the public key, so the signing secret exists only on your side; protect the private key file with a passphrase held in the secret store. OWASP also suggests scanning for secrets before commit, for example with a pre-commit hook, and auditing who accessed each secret and when.

## Logging without leaking secrets

Logs are copied to more places than any secret store, so secrets must be removed before a record is written. OWASP's Logging Cheat Sheet lists access tokens, encryption keys and other primary secrets among data that should be removed, masked or hashed rather than logged. Signed URLs are a common leak: the `signature` parameter and the API key header end up in debug output and error reports. A filter on the log handlers catches messages from your code and from libraries alike:

```python
import logging, os, re

class RedactSecrets(logging.Filter):
    """Mask known secrets and any signature= value before a record is written."""
    def __init__(self, *secrets):
        super().__init__()
        self.secrets = [s for s in secrets if s]
        self.signature = re.compile(r"(signature=)[^&\s]+")

    def filter(self, record):
        msg = record.getMessage()
        for s in self.secrets:
            msg = msg.replace(s, "[redacted]")
        record.msg, record.args = self.signature.sub(r"\1[redacted]", msg), None
        return True

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
api_key = os.environ.get("EXCHANGE_API_KEY", "hypothetical-key-123")
for handler in logging.getLogger().handlers:     # handler level also covers library loggers
    handler.addFilter(RedactSecrets(api_key))

logging.getLogger("urllib3").info("GET /api/v3/account?timestamp=1&signature=9f86d0 key=%s", api_key)
```

Output: `INFO urllib3 GET /api/v3/account?timestamp=1&signature=[redacted] key=[redacted]`. Log a key label or the last few characters instead of the key, and configure error-tracking tools to scrub request headers.

## Rotation, revocation and signs of a compromised key

Rotate keys on a schedule and revoke them at the first sign of trouble. OWASP describes a lifecycle of creation, rotation, revocation and expiration, with regular rotation so that stolen credentials work only for a short time. Warning signs include orders or fills you cannot attribute to your own systems, unknown open orders, unexpected balance changes, and security notifications about new keys or logins.

> **Hypothetical example.** At 03:12 the bot's user data stream reports a fill on a pair the strategy never trades. The operator revokes the key, cancels open orders, issues a new key restricted to the bot's IP, and then reviews which systems held the old secret, following OWASP's containment order of revocation, rotation, deletion of exposed copies and log review.

Binance's API documentation gives the same instruction for unusual account activity: revoke all keys immediately and contact support. Automate the steps you can, because a kill switch that needs a human to find the right page is slow; see [trading bot risk management](https://fincodelabs.com/en/blog/trading-bot-risk-management).

## Giving API keys to a third-party developer safely

A developer building your bot does not need your production keys during development, and never needs withdrawal rights. A safe pattern:

1. Develop and test on a testnet with testnet keys.
2. For go-live, create the production key yourself, with trade-only permission and an IP restriction to a server you control.
3. Put the secret straight into that server's secret store instead of sending it by chat or email; OWASP advises provisioning credentials over secure channels.
4. Fund a dedicated sub-account only with what the strategy needs.
5. Rotate the key when the engagement ends or access changes.

The same care applies to [AI assistants connected through an MCP server](https://fincodelabs.com/en/blog/crypto-trading-mcp-server): start read-only or on a demo account.

The broader integration practices behind this, such as signing, limits and reconnects, are covered in [crypto exchange API integration](https://fincodelabs.com/en/blog/crypto-exchange-api-integration), and integration work is described on the [exchange API integration](https://fincodelabs.com/en/services/exchange-api-integration) page. How software from Fincode handles keys is on its [security page](https://fincodelabs.com/en/security).

## Coinbase API key text scam: what to do about fake alerts

Treat an unexpected text saying an API key was created on your account as phishing until you have checked the account yourself. Coinbase's pages read on 4 November 2026 do not describe this exact message, but their rules cover it; the steps below apply them, and they work for any exchange.

1. **Do not use the link or number in the message.** Coinbase warns that anyone can send a text saying whatever they want and advises ignoring unsolicited texts and calls. In one pattern it describes, a text about a suspended transfer leads to a call from someone posing as Coinbase.
2. **Give nothing away.** Coinbase says it will never call you or ask for login credentials, an API key or two-factor codes. Bitget says its staff will never ask for an API key, secret key or passphrase.
3. **Check the account directly.** Open the exchange by typing its address and read the API key list. A key you did not create is a real compromise: revoke it and follow the rotation and revocation steps above.
4. **Report it.** Coinbase's Help Center asks for a screenshot of a phishing text sent to its security team, and US carriers accept copies of suspicious texts at 7726 (SPAM).

Coinbase also advises deleting unused or overprivileged API keys and rotating the rest, which limits the damage if such a message turns out to be real.

For readers in Turkey, Article 99/A of Capital Markets Law No. 6362 treats activity by foreign crypto-asset platforms directed at Turkish residents as unauthorized.

## Frequently asked questions

### Does a trading bot need withdrawal permission?

No. A trading bot only needs to read balances and orders and to place and cancel orders. Withdrawal and transfer rights add risk without adding function.

### Are environment variables safe for API keys?

They are better than hard-coding, but OWASP notes they are accessible to all processes and can leak into logs or dumps. In production, prefer a secrets manager.

### What does IP whitelisting protect against?

It makes a leaked key unusable from any address except yours. On Binance, HMAC keys without an IP restriction can by default only read data.

### How often should API keys be rotated?

There is no universal interval; Kraken simply advises rotating periodically. Rotate on a schedule you can automate, whenever people with access change, and immediately after any suspected exposure.

### Is Ed25519 more secure than HMAC for exchange API keys?

With Ed25519 you keep the private key and upload only the public key, so the exchange never holds your signing secret. Binance recommends Ed25519 and marks HMAC keys as deprecated.

### Is a text saying an API key was created real?

Treat it as phishing until you have checked the account yourself, without using the link in the message. Coinbase says it will never ask for an API key, login credentials or two-factor codes.

## Sources

- [OWASP Cheat Sheet Series: Secrets Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html)
- [OWASP Cheat Sheet Series: Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html)
- [Binance Spot API documentation: REST API (request security)](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md)
- [Binance Spot API documentation: API key types](https://github.com/binance/binance-spot-api-docs/blob/master/faqs/api_key_types.md)
- [Binance Support: How to Create API Keys on Binance](https://www.binance.com/en/support/faq/detail/360002502072)
- [Binance Wallet API: Get API Key Permission](https://developers.binance.com/en/docs/catalog/core-trading-wallet/api/rest-api/account#get-api-key-permission)
- [Kraken: API key permissions](https://docs.kraken.com/exchange/guides/rest/api-keys)
- [Kraken: Sub-accounts and multi-account management](https://docs.kraken.com/exchange/guides/general/subaccounts)
- [Coinbase App API key authentication](https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication)
- [TradingView: How to configure webhook alerts](https://www.tradingview.com/support/solutions/43000529348-how-to-configure-webhook-alerts/)
- [Coinbase Advanced Trade API: Get API Key Permissions](https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/data-api/get-api-key-permissions)
- [Coinbase Help: Reporting phishing sites (phishing texts)](https://help.coinbase.com/en/coinbase/privacy-and-security/avoiding-phishing-and-scams/reporting-phishing-sites)
- [Coinbase blog: Hang up the Phone, Stop Social Engineering Scams (February 3, 2025)](https://www.coinbase.com/blog/hang-up-the-phone-stop-social-engineering-scams)
- [Bitget API documentation: REST API (permissions, IP binding)](https://www.bitget.com/docs/uta/rest-api)
- [Bitget Academy: How to trade crypto on Bitget using TradingView (March 27, 2026)](https://www.bitget.com/academy/beginners-guide-to-using-tradingview-to-trade-crypto-on-bitget)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/api-key-security-trading-bots

Cite as: Fincode, "API key security for trading bots: permissions, storage", updated November 5, 2026, https://fincodelabs.com/en/blog/api-key-security-trading-bots
