Kriptomenjačnica
🐍
Napredni30 min reading

Python Crypto Bot — From Zero to First Trade

Step-by-step: ccxt library, strategy, backtesting and live trading on testnet.

Building a Crypto Bot with Python

Python is the most popular language for crypto bots. The ecosystem is rich: ccxt for exchange connectivity, pandas for data, ta-lib or pandas-ta for indicators, and backtrader or freqtrade for backtesting.

Setup

pip install ccxt pandas pandas-ta python-dotenv

Store API keys in a .env file — never hardcode them in your script.

Simple EMA Crossover Bot

Strategy: buy when the 9-period EMA crosses above the 21-period EMA; sell when it crosses below.

import ccxt, pandas as pd, pandas_ta as ta, time, os
from dotenv import load_dotenv
load_dotenv()

exchange = ccxt.binance({'apiKey': os.getenv('API_KEY'), 'secret': os.getenv('SECRET')})

def get_ohlcv(symbol='BTC/USDT', tf='1h', limit=100):
    data = exchange.fetch_ohlcv(symbol, tf, limit=limit)
    df = pd.DataFrame(data, columns=['time','open','high','low','close','volume'])
    df['ema9']  = ta.ema(df['close'], length=9)
    df['ema21'] = ta.ema(df['close'], length=21)
    return df

while True:
    df = get_ohlcv()
    if df['ema9'].iloc[-2] < df['ema21'].iloc[-2] and df['ema9'].iloc[-1] > df['ema21'].iloc[-1]:
        print('BUY signal')
        # exchange.create_market_buy_order('BTC/USDT', 0.001)
    time.sleep(60)

Backtesting First

Before running live, backtest on historical data. Use backtrader or freqtrade backtesting mode. Key metrics to evaluate: total return, max drawdown, win rate, Sharpe ratio.

Deployment

Run your bot on a VPS (DigitalOcean, Hetzner) for 24/7 uptime. Use tmux or systemd to keep it running. Log all trades to a CSV or database for monitoring.