How to Build a Crypto Trading Bot with Python (Step by Step, 2026)
A crypto trading bot is a program that reads market data from an exchange, decides when to buy or sell by fixed rules, and places the orders through the exchange API. Python is the most common language for this because of libraries like ccxt, which works with more than 100 exchanges using the same code. This guide builds a simple bot step by step and covers what it needs before it trades real money.
What you need
- Python 3 and a code editor.
- An exchange account with API access, for example Binance, Bybit, OKX or Kraken.
- The
ccxtandpandaslibraries:pip install ccxt pandas. - A testnet or demo account to start with. Binance and Bybit both offer one.
Step 1: Create API keys safely
In your exchange account, create an API key with trading permission only. Never enable withdrawals for a bot. If the exchange supports it, restrict the key to your server's IP address. Store the key in environment variables, not in your code:
export EXCHANGE_KEY="your-key"
export EXCHANGE_SECRET="your-secret"
Step 2: Connect and read market data
import os, ccxt, pandas as pd
ex = ccxt.binance({
"apiKey": os.environ["EXCHANGE_KEY"],
"secret": os.environ["EXCHANGE_SECRET"],
"enableRateLimit": True,
})
ex.set_sandbox_mode(True) # testnet while you build
def candles(symbol="BTC/USDT", tf="15m", limit=200):
raw = ex.fetch_ohlcv(symbol, tf, limit=limit)
df = pd.DataFrame(raw, columns=["time", "open", "high", "low", "close", "volume"])
df["time"] = pd.to_datetime(df["time"], unit="ms")
return df
enableRateLimit makes ccxt wait between requests so the exchange doesn't block you.
Step 3: Write the strategy as a function
Keep the strategy separate from the exchange code so you can test it on its own. This example uses two moving averages:
def signal(df, fast=20, slow=50):
f = df["close"].ewm(span=fast).mean()
s = df["close"].ewm(span=slow).mean()
if f.iloc[-2] <= s.iloc[-2] and f.iloc[-1] > s.iloc[-1]:
return "buy"
if f.iloc[-2] >= s.iloc[-2] and f.iloc[-1] < s.iloc[-1]:
return "sell"
return None
Use closed candles for signals. The last candle in the list is usually still forming, so many bots drop it before calculating.
Step 4: Size the position and place the order
RISK_USDT = 50 # amount to spend per trade
def place(side, symbol="BTC/USDT"):
ex.load_markets()
price = ex.fetch_ticker(symbol)["last"]
amount = float(ex.amount_to_precision(symbol, RISK_USDT / price))
if amount < ex.market(symbol)["limits"]["amount"]["min"]:
print("order too small"); return None
return ex.create_order(symbol, "market", side, amount)
amount_to_precision rounds the size to what the exchange accepts. Without it, many orders are rejected.
Step 5: Run the loop
import time
position = None
while True:
try:
df = candles().iloc[:-1] # closed candles only
s = signal(df)
if s == "buy" and position is None:
place("buy"); position = "long"
elif s == "sell" and position == "long":
place("sell"); position = None
except ccxt.NetworkError as e:
print("network error, retrying", e)
except ccxt.ExchangeError as e:
print("exchange error", e)
time.sleep(60)
This is the minimum. A real bot reads its actual balance and open orders from the exchange at start-up instead of trusting a variable, so a restart never causes a double buy.
What a live crypto bot also needs
- Stop loss and limits: a maximum loss per trade and per day, and a kill switch.
- State from the exchange: always check real positions and balances before acting.
- Partial fills and fees: the amount you receive is smaller than the amount you ordered.
- Logging and alerts: send every trade and error to Telegram or Discord.
- Hosting: run it on a VPS so it keeps working when your computer is off.
- Backtesting: test the strategy on historical candles, including fees, before using real money.
Frequently asked questions
Is Python good for crypto trading bots?
Yes. It is the most popular choice for strategy bots, with ccxt for exchanges and pandas for data. Only very high-frequency strategies need faster languages.
Are crypto trading bots legal?
In most countries, using a bot on your own account is legal, and major exchanges provide APIs for exactly this. Check your local rules and the exchange's terms.
Can a bot trade futures?
Yes. ccxt supports futures on many exchanges, but leverage multiplies losses, so risk limits matter even more.
How much does a custom crypto bot cost?
Most custom crypto bots cost a few hundred to a few thousand dollars depending on the strategy and exchanges. See our trading bot cost guide.
Want a crypto bot built for you?
We build crypto trading bots in Python for Binance, Bybit and other exchanges, with risk limits, Telegram alerts and VPS hosting. See custom trading bot development. Related: Telegram crypto signal bot with Python.