CodeForFinance
Python Tutorial

Python Crypto Trading Bot Tutorial

Build an automated cryptocurrency trading bot using Python, ccxt, and simple moving average crossover strategy.

Install

pip install ccxt pandas numpy

Connect to Exchange

import ccxt
import pandas as pd
import time

# Connect to Binance (use testnet for practice)
exchange = ccxt.binance({
    "apiKey": "YOUR_API_KEY",
    "secret": "YOUR_SECRET",
    "sandbox": True,  # Use testnet
})

# Fetch BTC/USDT price
ticker = exchange.fetch_ticker("BTC/USDT")
print(f"BTC Price: ${ticker['last']:,.2f}")
print(f"24h Volume: ${ticker['quoteVolume']:,.0f}")

Get Historical Data

# Fetch 1h candles
ohlcv = exchange.fetch_ohlcv("BTC/USDT", "1h", limit=100)
df = pd.DataFrame(ohlcv, columns=["timestamp", "open", "high", "low", "close", "volume"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")

# Calculate moving averages
df["SMA_20"] = df["close"].rolling(20).mean()
df["SMA_50"] = df["close"].rolling(50).mean()

print(df[["timestamp", "close", "SMA_20", "SMA_50"]].tail(10))

Trading Signal

# Simple crossover signal
df["signal"] = 0
df.loc[df["SMA_20"] > df["SMA_50"], "signal"] = 1   # Buy
df.loc[df["SMA_20"] < df["SMA_50"], "signal"] = -1  # Sell

current = df.iloc[-1]
if current["signal"] == 1:
    print("SIGNAL: BUY — Short MA above Long MA")
elif current["signal"] == -1:
    print("SIGNAL: SELL — Short MA below Long MA")
else:
    print("SIGNAL: HOLD")

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.