StructureX

Home › Guides › Trading bots & code

API key security for trading bots: keep the keys to your account safe

An API key is a password that lets code act on your account. Anyone who has it can trade as you. Here's how to keep keys out of your code, out of your logs and out of other people's hands.

Beginner guide · 10-minute read · Updated 2026-10-21

What an API key is

An API is the door a program uses to talk to a broker or exchange. The API key (and its partner, the secret) is the key to that door.

With it, code can read your balance and place orders — without your password and often without your phone code. That's what makes bots possible. It's also why a leaked key is serious.

Treat every key like the PIN to your bank card.

Example code for learning — test it on paper first; it is not a ready-made trading system.

Rule 1: Never put keys in your code

This is the classic leak:

Instead, keep keys in environment variables. That's a setting stored by your computer, outside the code. The code asks for it by name.

On Mac or Linux, in the terminal (use paper or testnet keys while learning):

export EXCHANGE_API_KEY="paste-your-key-here"
export EXCHANGE_API_SECRET="paste-your-secret-here"

On Windows PowerShell:

$env:EXCHANGE_API_KEY = "paste-your-key-here"
$env:EXCHANGE_API_SECRET = "paste-your-secret-here"

These last until you close the window. To keep them, people often use a file called .env loaded by their code — and then make sure that file is never shared or committed.

Rule 2: Read keys safely, fail loudly

import os
def get_secret(name):
    """Read a key from the environment. Stop if it's missing."""
    value = os.environ.get(name)
    if not value:
        raise SystemExit(f"Missing {name}. Set it as an environment variable.")
    return value
def masked(secret):
    """Safe to print: shows only the first 4 characters."""
    return f"{secret[:4]}... ({len(secret)} characters)"
api_key = get_secret("EXCHANGE_API_KEY")
api_secret = get_secret("EXCHANGE_API_SECRET")
print("Using key", masked(api_key))

In plain words:

Here's how those keys reach an exchange using the ccxt library (more in crypto trading bot with ccxt). This only builds the connection object; it doesn't place anything.

import ccxt
exchange_id = get_secret("EXCHANGE_ID")            # your exchange's ccxt name
exchange = getattr(ccxt, exchange_id)({
    "apiKey": api_key,
    "secret": api_secret,
    "enableRateLimit": True,
})
exchange.set_sandbox_mode(True)    # testnet only; raises an error if your exchange has none

The keys come from the environment, never from the file. Learn on testnet or paper keys first — see paper trading a bot.

Rule 3: Keep keys out of your logs

Bots log a lot. That's good — until an error message prints the request, key and all. A small filter wipes the secret from every log line before it's written:

import logging
class HideSecrets(logging.Filter):
    def __init__(self, secrets):
        super().__init__()
        self.secrets = [s for s in secrets if s]
    def filter(self, record):
        msg = record.getMessage()
        for s in self.secrets:
            msg = msg.replace(s, "[HIDDEN]")
        record.msg, record.args = msg, ()
        return True
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("bot")
log.addFilter(HideSecrets([api_key, api_secret]))
log.error(f"request failed, key={api_key}")       # prints: key=[HIDDEN]

It's a safety net, not a licence to log keys. The best log line is one that never contained the key.

Rule 4: Give each key the least power it needs

Most brokers and exchanges let you choose what a key can do when you create it. Look for these settings:

SettingWhat to chooseWhy
Read / viewOnThe bot needs balances and orders
TradeOn only for a trading botA bot that only reads data doesn't need it
Withdraw / transferOff. Always.A stolen trade-only key can't send your money out
IP whitelist (IP limit)Your server's addressThe key works only from that machine

Withdrawals off is the single most important tick box. A bot never needs to move money out.

IP whitelisting means the key only works from an internet address you list. If someone steals the key, it fails from their computer. Use it wherever it's offered.

Rule 5: One key per job

Rule 6: Never share a key — with anyone

Not in a chat group. Not in a support ticket. Not in an AI chat assistant. Not with a "bot seller".

Here's the thing: any service that asks for your keys with withdrawals turned on, or asks you to "connect your account" so their bot can trade it for guaranteed returns, is a classic scam shape. US regulators have warned about trading-bot and AI-trading scams. Before trusting anyone, check AI trading scams to avoid and the warnings on investor.gov.

Rule 7: Lock the account itself

The minute a key leaks

You pushed it to GitHub, pasted it somewhere, or something looks odd. Do this right away, in this order:

  1. Revoke the key in your broker or exchange settings. Deleting it from your code is not enough — it's already been copied.
  2. Check the account: open orders, positions, any transfers. Cancel anything you didn't place.
  3. Make a new key with the least power it needs, and update your environment variable.
  4. Find how it leaked and fix that, so it doesn't happen twice.
  5. If anything moved that you didn't do, contact the broker's support at once.

Removing a key from GitHub history isn't enough either. Assume anything that was public was copied.

Add .env to .gitignore before you write a single key. The .gitignore file tells Git which files never to save. Put .env in it first, then create the .env file.

Common mistakes

Questions

Where should I store API keys for a trading bot?

In environment variables or a secrets manager, never in the code. If you use a .env file, keep it out of Git and never share it.

Should my trading bot API key have withdrawal permission?

No. A trading bot never needs to withdraw. Turning withdrawals off means a stolen key can't move money out of the account.

What is IP whitelisting for API keys?

It limits a key so it only works from internet addresses you list, like your server's. A stolen key then fails from anywhere else.

What do I do if I leaked my API key on GitHub?

Revoke it in your broker or exchange settings at once, check the account for activity you didn't do, then make a new, limited key. Deleting the file doesn't undo the leak.

Want the next step? We'll walk you through it.

Four free lessons by email, one every few days — each with a 10-minute exercise on a real chart.

Send Me the Free Lessons 4 short emails · No spam · Unsubscribe anytime

Or see the whole method, step by step:

See What’s Inside the Course Try everything free first. Decide when you're ready. · Open the free chart tool (works in the TradingView phone app)

One chart idea a day, in plain English. Follow along:

Follow on XFollow on TradingView