Welcome to Capstone Project 1! Over Phase 3, you built every core piece of a real algorithmic trading system:
- Lesson 11: Custom indicators (
EMA,RSI,SMA) in pure Python. - Lesson 12 & 13: Strategy simulation and realistic friction awareness.
- Lesson 14: A
RiskManagersafety gatekeeper that sizes positions and blocks oversized bets.
Now we put everything together and solve the final hurdle: keeping your bot running 24/7 without leaving your laptop open. Crypto markets never close—if your laptop goes to sleep or your home Wi-Fi drops, your bot goes blind.
The cleanest way to run a bot 24/7 on a $5/month cloud server (like DigitalOcean, Hetzner, or AWS Lightsail) is Docker. Docker wraps your Python code, dependencies, and environment settings into a self-contained box ("container") that automatically restarts if it ever crashes or the server reboots.
Educational Note: This capstone bot connects exclusively to Binance Spot Testnet (
https://testnet.binance.vision) using free virtual funds. Never hardcode real API keys into your code, and never run untested bots with real money—this project is strictly educational and not financial advice.
Project Architecture
Create a new folder named lesson-15-capstone-rule-bot/ with these five files:
lesson-15-capstone-rule-bot/
├── bot.py # Main 24/7 trading loop (indicators + risk + Testnet orders)
├── requirements.txt # Python dependencies
├── .env # Your Binance Testnet API keys (NEVER commit to Git!)
├── Dockerfile # Blueprint to package the bot
└── docker-compose.yml # 1-command launcher with automatic 24/7 restarts
Prerequisites
- Local Testing: Python 3.10+ (
pip install -r requirements.txt). - 24/7 Cloud Hosting: Docker Desktop locally or Docker installed on any Linux cloud VPS.
- Binance Spot Testnet Keys: Generate free paper-trading API keys at testnet.binance.vision.
1. requirements.txt
ccxt==4.4.40
pandas==2.2.3
python-dotenv==1.0.1
2. .env (Keep Private!)
BINANCE_TESTNET_API_KEY=your_testnet_api_key_here
BINANCE_TESTNET_API_SECRET=your_testnet_api_secret_here
SYMBOL=BTC/USDT
TIMEFRAME=15m
CHECK_INTERVAL_SECONDS=60
3. The Complete Rule-Based Bot (bot.py)
This script wakes up every 60 seconds, fetches recent candles from Binance Testnet, calculates EMA 10, EMA 30, and RSI 14, checks our RiskManager, and places paper market orders only when a clean signal fires.
"""
Lesson 15: Capstone Project 1 — 24/7 Rule-Based Binance Testnet Bot
Combines custom indicators, risk-based position sizing, and safe 24/7 logging.
"""
import logging
import os
import time
import ccxt
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
# Configure clean timestamped logs (visible in `docker compose logs -f`)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)-7s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("BitfosterBot")
SYMBOL = os.getenv("SYMBOL", "BTC/USDT")
TIMEFRAME = os.getenv("TIMEFRAME", "15m")
CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL_SECONDS", "60"))
# Risk controls (from Lesson 14)
MAX_RISK_PER_TRADE_PCT = 0.01 # Risk 1% of USDT equity per trade
STOP_LOSS_PCT = 0.02 # 2% protective stop distance
MAX_POSITION_PCT = 0.20 # Never allocate > 20% of equity to one trade
MIN_NOTIONAL_USD = 15.0 # Safe buffer above Binance's $10 minimum
def create_testnet_exchange() -> ccxt.binance:
"""Initialize CCXT pointed strictly at Binance Spot Testnet."""
api_key = os.getenv("BINANCE_TESTNET_API_KEY")
api_secret = os.getenv("BINANCE_TESTNET_API_SECRET")
if not api_key or not api_secret:
raise ValueError("Missing BINANCE_TESTNET_API_KEY or BINANCE_TESTNET_API_SECRET in .env")
exchange = ccxt.binance({
"apiKey": api_key,
"secret": api_secret,
"enableRateLimit": True,
"options": {"defaultType": "spot"},
})
# CRITICAL: Sandbox mode routes all orders to Binance Spot Testnet
exchange.set_sandbox_mode(True)
return exchange
def fetch_indicators(exchange: ccxt.binance) -> pd.DataFrame:
"""Fetch OHLCV candles and compute EMA(10), EMA(30), and RSI(14)."""
ohlcv = exchange.fetch_ohlcv(SYMBOL, timeframe=TIMEFRAME, limit=100)
df = pd.DataFrame(ohlcv, columns=["timestamp", "open", "high", "low", "close", "volume"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
df["ema_fast"] = df["close"].ewm(span=10, adjust=False).mean()
df["ema_slow"] = df["close"].ewm(span=30, adjust=False).mean()
delta = df["close"].diff()
gains = delta.clip(lower=0).ewm(alpha=1 / 14, min_periods=14, adjust=False).mean()
losses = (-delta.clip(upper=0)).ewm(alpha=1 / 14, min_periods=14, adjust=False).mean()
rs = gains / losses.replace(0, float("nan"))
df["rsi_14"] = (100 - (100 / (1 + rs))).fillna(50.0)
return df
def calculate_safe_buy_qty(usdt_balance: float, price: float) -> float:
"""Calculate risk-managed BTC quantity using stop-loss distance and position cap."""
risk_dollars = usdt_balance * MAX_RISK_PER_TRADE_PCT
risk_per_btc = price * STOP_LOSS_PCT
raw_qty = risk_dollars / risk_per_btc
max_notional = usdt_balance * MAX_POSITION_PCT
final_notional = min(raw_qty * price, max_notional)
if final_notional < MIN_NOTIONAL_USD:
return 0.0
return final_notional / price
def run_bot_cycle(exchange: ccxt.binance, state: dict) -> None:
"""Run one complete check-and-trade cycle using the latest CLOSED candle."""
df = fetch_indicators(exchange)
# Use iloc[-2] (the most recently CLOSED candle) to avoid acting on half-formed bars!
closed = df.iloc[-2]
live_price = float(df.iloc[-1]["close"])
balance = exchange.fetch_balance()
usdt_free = float(balance["free"].get("USDT", 0.0))
base_coin = SYMBOL.split("/")[0]
btc_free = float(balance["free"].get(base_coin, 0.0))
in_position = (btc_free * live_price) >= MIN_NOTIONAL_USD
logger.info(
"%s | Price: $%.2f | EMA10: %.2f | EMA30: %.2f | RSI: %.1f | USDT: $%.2f | InPos: %s",
SYMBOL, live_price, closed["ema_fast"], closed["ema_slow"],
closed["rsi_14"], usdt_free, in_position,
)
# ENTRY RULE: Bullish EMA crossover + RSI not overbought (< 68)
if not in_position and closed["ema_fast"] > closed["ema_slow"] and closed["rsi_14"] < 68:
qty = calculate_safe_buy_qty(usdt_free, live_price)
if qty > 0:
rounded_qty = float(exchange.amount_to_precision(SYMBOL, qty))
order = exchange.create_market_buy_order(SYMBOL, rounded_qty)
state["entry_price"] = float(order.get("average") or live_price)
logger.info("BUY EXECUTED (Testnet) | Qty: %.6f %s @ ~$%.2f", rounded_qty, base_coin, state["entry_price"])
else:
logger.warning("BUY SKIPPED: Position size below minimum notional ($%.2f).", MIN_NOTIONAL_USD)
# EXIT RULE: Bearish EMA cross OR protective 2% stop-loss hit
elif in_position:
entry = state.get("entry_price")
stop_hit = entry is not None and live_price <= entry * (1 - STOP_LOSS_PCT)
trend_flipped = closed["ema_fast"] < closed["ema_slow"]
if stop_hit or trend_flipped:
reason = "STOP-LOSS HIT" if stop_hit else "EMA BEARISH CROSS"
rounded_qty = float(exchange.amount_to_precision(SYMBOL, btc_free))
exchange.create_market_sell_order(SYMBOL, rounded_qty)
logger.info("SELL EXECUTED (Testnet) | Reason: %s | Qty: %.6f %s @ ~$%.2f", reason, rounded_qty, base_coin, live_price)
state["entry_price"] = None
def main() -> None:
logger.info("Starting Bitfoster Rule-Based Bot on BINANCE TESTNET (%s, %s)", SYMBOL, TIMEFRAME)
exchange = create_testnet_exchange()
exchange.load_markets()
state = {"entry_price": None}
while True:
try:
run_bot_cycle(exchange, state)
except ccxt.NetworkError as e:
logger.warning("Temporary network hiccup (will retry): %s", e)
except Exception as e:
logger.error("Unexpected error in bot cycle: %s", e)
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
main()
4. Packaging for 24/7 Cloud Hosting (Dockerfile & docker-compose.yml)
Dockerfile
FROM python:3.11-slim
WORKDIR /app
# Install dependencies first for faster rebuilds
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy bot source code
COPY bot.py .
# Force unbuffered logs so `docker compose logs -f` prints immediately
ENV PYTHONUNBUFFERED=1
CMD ["python", "bot.py"]
docker-compose.yml
services:
trading-bot:
build: .
container_name: bitfoster-rule-bot
env_file:
- .env
restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
Launching Your 24/7 Bot
Whether you are testing on your own computer or SSH'd into a cloud VPS, launching your bot takes one command:
docker compose up -d --build
Stream live logs anytime (press Ctrl+C to stop watching—your bot keeps running in the background!):
docker compose logs -f
To safely stop the bot:
docker compose down
Expected Terminal Output
bitfoster-rule-bot | 2026-12-03 11:00:02 | INFO | Starting Bitfoster Rule-Based Bot on BINANCE TESTNET (BTC/USDT, 15m)
bitfoster-rule-bot | 2026-12-03 11:00:04 | INFO | BTC/USDT | Price: $94,790.10 | EMA10: 94612.40 | EMA30: 94480.15 | RSI: 58.3 | USDT: $10,000.00 | InPos: False
bitfoster-rule-bot | 2026-12-03 11:00:05 | INFO | BUY EXECUTED (Testnet) | Qty: 0.021099 BTC @ ~$94,792.00
bitfoster-rule-bot | 2026-12-03 11:01:05 | INFO | BTC/USDT | Price: $94,815.50 | EMA10: 94612.40 | EMA30: 94480.15 | RSI: 58.3 | USDT: $8,000.00 | InPos: True
Common Beginner Mistake: Reading
df.iloc[-1](the currently forming live candle) for indicator crossover signals. Because the current candle's price is still bouncing up and down, an EMA can cross back and forth 5 times in one minute, causing erratic trades. Always readdf.iloc[-2]—the most recently closed candle—for clean, stable signals.
Study & Practice Recap
- Never run a 24/7 bot without
try/exceptandrestart: unless-stopped: Exchange APIs occasionally time out; catching network errors inside your loop and letting Docker auto-restart keeps your bot resilient. - Always separate secrets from code: Keep API keys in
.env(and add.envto.gitignore) so you never accidentally push credentials to GitHub. - Watch your logs and disk space: Setting
max-size: "10m"indocker-compose.ymlensures months of 24/7 logs never fill up your cloud server's hard drive.
Tiny Hands-On Exercise: Run docker compose up -d --build with your Binance Testnet keys, watch it log 3 consecutive cycles with docker compose logs -f, and then add a simple Take-Profit condition (live_price >= entry * 1.04) right alongside stop_hit in bot.py!