DEV Community

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

Posted on

How 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. ๐Ÿ‘‡

Top comments (1)

Collapse
 
peter_tosin_9ce22e11eee93 profile image
Peter Tosin

I want to create a trading bot using python and machine learning with some indicator cam we chat up ?