Wednesday, April 23, 2025

How I Built a Real-Time Crypto Trading Bot in Python (With Code!)

Programming LanguageHow I Built a Real-Time Crypto Trading Bot in Python (With Code!)


Crypto automation sounds exciting: a bot that trades while you sleep, catches profitable trends, and never gets tired.

But when I started exploring the space, most bots I found were either overhyped, under-documented, or flat-out broken.

So I decided to build my own bot from scratch—one that works in real time, with full control from the command line, supports backtesting, paper trading, and can deploy to a $5 VPS.

This post covers my journey from zero to real-time execution bot. If you’re a Python dev or a trader curious about bot building, this one’s for you.


🧱 Planning the Bot: Goals and Features

Before writing a single line of code, I outlined the core requirements:

  • ✅ Real-time strategy execution using Binance API
  • ✅ CLI-based interface for strategy selection and control
  • ✅ Strategy modularity (plug-in based system)
  • ✅ Support for backtesting and paper/live modes
  • ✅ Logging of trades and errors
  • ✅ Lightweight for VPS deployment

🧰 Tech Stack I Used

  • Python 3.10+
  • Binance API via python-binance
  • TA-Lib / pandas-ta for technical indicators
  • pandas / NumPy for data processing
  • SQLite for optional trade logging
  • argparse or Typer for CLI interface

📐 Project Architecture

crypto_bot/
├── strategies/
│   ├── rsi_strategy.py
│   ├── macd_strategy.py
├── core/
│   ├── trader.py
│   ├── logger.py
├── config/
│   └── settings.json
├── cli.py
├── bot.py
└── logs/
Enter fullscreen mode

Exit fullscreen mode

  • Strategies: Each is a pluggable Python class
  • Trader: Handles data fetching and order execution
  • Logger: Manages session logs and optional SQLite
  • CLI: Launches bot with selected strategy and symbol

🔁 Real-Time Trading Loop (Core Logic)

Here’s a simplified version of the loop:

while True:
    df = fetch_ohlcv(symbol, interval)
    signal = strategy.evaluate(df)
    if signal == "BUY":
        trader.buy(symbol, quantity)
    elif signal == "SELL":
        trader.sell(symbol, quantity)
    sleep(next_candle_time())
Enter fullscreen mode

Exit fullscreen mode

This ensures:

  • Continuous data pulling
  • Strategy evaluation per new candle
  • Instant execution for valid signals

📊 Strategy Example: RSI Strategy (Modular)

class RSIStrategy:
    def __init__(self, period=14, overbought=70, oversold=30):
        self.period = period
        self.overbought = overbought
        self.oversold = oversold

    def evaluate(self, df):
        df['rsi'] = ta.rsi(df['close'], length=self.period)
        if df['rsi'].iloc[-1] < self.oversold:
            return "BUY"
        elif df['rsi'].iloc[-1] > self.overbought:
            return "SELL"
        return "HOLD"
Enter fullscreen mode

Exit fullscreen mode

New strategies can follow this simple class-based structure.


💻 CLI Control: Run Strategies from Terminal

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--symbol', type=str, required=True)
parser.add_argument('--strategy', type=str, required=True)
parser.add_argument('--mode', choices=['paper', 'live'], default='paper')
args = parser.parse_args()

bot = TradingBot(symbol=args.symbol, strategy=args.strategy, mode=args.mode)
bot.run()
Enter fullscreen mode

Exit fullscreen mode

Launch your bot like this:

python cli.py --symbol BTCUSDT --strategy rsi --mode paper
Enter fullscreen mode

Exit fullscreen mode


🧪 Backtesting & Paper Trading Support

The bot has:

  • Historical simulation with CSV or Binance fetch
  • Paper mode that logs trades without placing them
  • Live switch for actual order placement after testing

Sample output:

[2025-04-23 14:22:01] BUY BTCUSDT at 62410.5 [RSI: 29.7]
Enter fullscreen mode

Exit fullscreen mode


📋 Logging & Trade History

Choose between:

  • Plain text log files
  • SQLite logging for deeper analysis and dashboards

Sample session log:

[INFO] RSI crossed below 30. Triggering BUY signal.
[EXECUTE] Simulated BUY 0.01 BTC at 61,420.20
Enter fullscreen mode

Exit fullscreen mode


☁️ VPS Deployment (DigitalOcean or Similar)

I deployed the bot on a $5/month droplet:

  1. Setup Python & virtualenv
  2. Clone the repo
  3. Run the bot using screen or tmux
  4. Use tail -f logs/session.log to monitor

It runs 24/7 on minimal resources.


🧠 Lessons Learned

  • Always test with paper mode first
  • Logging is essential—debugging without it is chaos
  • Modular code = less burnout
  • Don’t over-engineer your strategies—simple works
  • Expect API hiccups and plan for recovery

📘 Want to Build This Bot Too?

I turned the full journey into a 250+ page guide with all code included.

📥 Download the PDF Guide: https://shop.matrixtrak.com

💻 Access the Full Python Bot Repo: https://shop.matrixtrak.com/b/gWzRM


🚀 Final Thoughts

This bot evolved from a weekend project to a full trading framework I now trust with real money.

Whether you’re a dev, trader, or learner—building your own crypto bot teaches you way more than using a prebuilt tool.

Let me know if you’re working on something similar, or want feedback on your strategy code. 👇

Check out our other content

Check out other tags:

Most Popular Articles