Educational Disclaimer & Safety First: This capstone project is strictly an educational engineering blueprint and is not financial advice. It is hard-wired to Binance Testnet (
set_sandbox_mode(True)), defaults to safe simulated paper fills when Testnet API keys are omitted, and binds its FastAPI monitoring dashboard strictly to127.0.0.1so your Stop Bot button is never exposed to the open internet.
Putting Every Layer Together: Defense-in-Depth Architecture
Over Phases 1 through 5, you built individual superpowers: clean candle pipelines, market mood detection, crash protection, LightGBM prediction, position-sizing risk limits, and a local web dashboard.
Now we connect them into one disciplined decision funnel. Notice the order of the gates—your AI model is not allowed to place a trade on its own!
Binance Testnet Candles (5m)
│
▼
[1] Shared Feature Engine (drop unclosed candle -> identical to training)
│
▼
[2] Crash Filter / Circuit Breaker (halt immediately on sudden drop or extreme vol)
│
▼
[3] Market Mood Detector (only allow long entries in constructive/neutral regimes)
│
▼
[4] LightGBM Predictor (require probability >= 0.58 to open a position)
│
▼
[5] Risk Manager (max position size, stop-loss, take-profit, daily loss cap)
│
▼
[6] Binance Testnet Executor ◄──► [7] Local FastAPI Dashboard (127.0.0.1:8000)
Why This Layered Architecture Matters
- Separation of concerns: Each gate is its own small Python function with one job. If you want to tighten your crash threshold or swap LightGBM for another model later, you only edit that one gate.
- Safety overrides intelligence: Even if LightGBM outputs
92%bullish confidence, the Crash Filter and Risk Manager have absolute veto power. Machines are great at finding patterns, but rules keep accounts alive during black-swan spikes. - Zero-friction reproducibility: On startup, if
capstone_lgbm.joblibdoes not exist yet, the bot automatically trains a fresh baseline model using the exact samebuild_features()function it uses for live inference—guaranteeing zero training-serving skew from minute one. - Visual peace of mind: Running the FastAPI dashboard on
127.0.0.1:8000in the same process lets you watch every gate's decision live and hit Emergency Stop with a single click.
Prerequisites
Install all required packages:
pip install ccxt pandas numpy lightgbm joblib fastapi uvicorn
(Optional) If you want the bot to submit real sandbox orders to your Binance Spot Testnet account instead of local simulated Testnet fills, export your Testnet-only keys before running:
export BINANCE_TESTNET_API_KEY="your_testnet_key"
export BINANCE_TESTNET_SECRET="your_testnet_secret"
Never put real-money Binance keys into these environment variables.
Complete Runnable Capstone Bot (capstone_ai_bot.py)
Save the following file as capstone_ai_bot.py. It is 100% self-contained and copy-and-paste runnable.
# capstone_ai_bot.py
"""
Lesson 24: Capstone Project 2 — Complete AI-Filtered Trading Bot
Connects:
1. Shared Feature Engine (offline + live parity)
2. Crash Filter (volatility & flash-drop circuit breaker)
3. Market Mood Detector (EMA trend regime)
4. LightGBM Predictor
5. Risk Manager (fixed sizing, SL/TP, max daily loss)
6. Binance Testnet Executor (sandbox mode + safe dry-run fallback)
7. Local-Only FastAPI Dashboard (127.0.0.1:8000)
"""
from contextlib import asynccontextmanager
from datetime import datetime, timezone
import os
from pathlib import Path
import threading
from typing import Any, Dict, List, Optional, Tuple
import ccxt
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import joblib
import lightgbm as lgb
import numpy as np
import pandas as pd
from pydantic import BaseModel
import uvicorn
# ==============================================================================
# CONFIGURATION (Binance Testnet Only)
# ==============================================================================
SYMBOL = "BTC/USDT"
TIMEFRAME = "5m"
MODEL_PATH = Path("capstone_lgbm.joblib")
POLL_SECONDS = 15
AI_BUY_THRESHOLD = 0.58 # Minimum LightGBM probability to enter long
CRASH_DROP_THRESHOLD = -0.025 # Halt if 1-candle return <= -2.5%
CRASH_VOL_THRESHOLD = 0.015 # Halt if 12-candle realized vol >= 1.5%
STOP_LOSS_PCT = 0.010 # 1.0% stop-loss
TAKE_PROFIT_PCT = 0.018 # 1.8% take-profit
MAX_DAILY_LOSS_USDT = 150.0 # Daily circuit breaker
POSITION_SIZE_USDT = 500.0 # Fixed notional per Testnet trade
FEATURE_COLUMNS: List[str] = [
"return_1",
"return_3",
"return_6",
"ema_gap_9_21",
"rsi_14",
"volatility_12",
"volume_ratio_12",
]
# ==============================================================================
# 1. SHARED FEATURE ENGINE (Identical for Training & Live Trading)
# ==============================================================================
def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
delta = close.diff()
gains = delta.clip(lower=0.0)
losses = -delta.clip(upper=0.0)
avg_gain = gains.ewm(alpha=1 / period, adjust=False, min_periods=period).mean()
avg_loss = losses.ewm(alpha=1 / period, adjust=False, min_periods=period).mean()
rs = avg_gain / avg_loss.replace(0.0, np.nan)
return (100.0 - (100.0 / (1.0 + rs))).fillna(50.0)
def build_features(df: pd.DataFrame, drop_unclosed_last_candle: bool = False) -> pd.DataFrame:
data = df.copy().sort_values("timestamp").reset_index(drop=True)
if drop_unclosed_last_candle:
data = data.iloc[:-1].copy()
close = data["close"].astype(float)
volume = data["volume"].astype(float)
data["return_1"] = close.pct_change(1)
data["return_3"] = close.pct_change(3)
data["return_6"] = close.pct_change(6)
ema_fast = close.ewm(span=9, adjust=False).mean()
ema_slow = close.ewm(span=21, adjust=False).mean()
data["ema_gap_9_21"] = (ema_fast - ema_slow) / ema_slow
data["rsi_14"] = compute_rsi(close, period=14) / 100.0
data["volatility_12"] = data["return_1"].rolling(12).std()
avg_vol = volume.rolling(12).mean().replace(0.0, np.nan)
data["volume_ratio_12"] = (volume / avg_vol).fillna(1.0)
return data.dropna(subset=FEATURE_COLUMNS).reset_index(drop=True)
# ==============================================================================
# 2. CRASH FILTER & 3. MARKET MOOD DETECTOR
# ==============================================================================
def check_crash_filter(latest_row: pd.Series) -> Tuple[bool, str]:
"""Return (is_safe, reason). Vetoes trading during flash crashes or extreme volatility."""
ret1 = float(latest_row["return_1"])
vol12 = float(latest_row["volatility_12"])
if ret1 <= CRASH_DROP_THRESHOLD:
return False, f"CRASH HALT: 1-bar drop {ret1*100:.2f}%"
if vol12 >= CRASH_VOL_THRESHOLD:
return False, f"CRASH HALT: high vol {vol12*100:.2f}%"
return True, "OK"
def detect_market_mood(latest_row: pd.Series) -> str:
"""Classify current market regime from normalized EMA spread."""
gap = float(latest_row["ema_gap_9_21"])
if gap > 0.0010:
return "BULLISH"
if gap < -0.0015:
return "BEARISH"
return "NEUTRAL"
# ==============================================================================
# 4. LIGHTGBM MODEL LOADER / AUTO-TRAINER
# ==============================================================================
def load_or_train_model(candles_df: pd.DataFrame) -> Dict[str, Any]:
if MODEL_PATH.exists():
bundle = joblib.load(MODEL_PATH)
if bundle.get("feature_columns") == FEATURE_COLUMNS:
return bundle
feat_df = build_features(candles_df, drop_unclosed_last_candle=True)
feat_df["target"] = (feat_df["close"].shift(-1) > feat_df["close"]).astype(int)
train_df = feat_df.iloc[:-1].copy()
model = lgb.LGBMClassifier(
n_estimators=80,
learning_rate=0.05,
max_depth=4,
num_leaves=15,
random_state=42,
verbose=-1,
)
model.fit(train_df[FEATURE_COLUMNS], train_df["target"])
bundle = {"model": model, "feature_columns": FEATURE_COLUMNS}
joblib.dump(bundle, MODEL_PATH)
return bundle
# ==============================================================================
# 5. RISK MANAGER & 6. BINANCE TESTNET EXECUTOR
# ==============================================================================
state_lock = threading.Lock()
stop_event = threading.Event()
bot_state: Dict[str, Any] = {
"status": "RUNNING",
"execution_mode": "TESTNET SIMULATED",
"symbol": SYMBOL,
"last_price": 0.0,
"market_mood": "NEUTRAL",
"crash_status": "OK",
"ai_prob_up": 0.50,
"daily_pnl_usdt": 0.0,
"position": None, # None or {"qty": float, "entry_price": float}
"last_decision": "Initializing...",
"last_updated": "--",
"events": [],
}
def add_event(msg: str) -> None:
ts = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")
bot_state["events"].insert(0, f"[{ts}] {msg}")
del bot_state["events"][15:]
def create_testnet_exchange() -> Tuple[ccxt.binance, bool]:
api_key = os.getenv("BINANCE_TESTNET_API_KEY", "").strip()
secret = os.getenv("BINANCE_TESTNET_SECRET", "").strip()
has_keys = bool(api_key and secret)
exchange = ccxt.binance({
"apiKey": api_key if has_keys else None,
"secret": secret if has_keys else None,
"enableRateLimit": True,
})
exchange.set_sandbox_mode(True) # Always enforce Binance Spot Testnet!
return exchange, has_keys
def fetch_ohlcv_df(exchange: ccxt.binance, limit: int = 250) -> pd.DataFrame:
raw = exchange.fetch_ohlcv(SYMBOL, timeframe=TIMEFRAME, limit=limit)
df = pd.DataFrame(raw, columns=["timestamp", "open", "high", "low", "close", "volume"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
return df
def execute_testnet_order(
exchange: ccxt.binance, has_keys: bool, side: str, qty: float, price: float
) -> str:
"""Place a Binance Testnet market order if keys exist, else record a simulated Testnet fill."""
qty = round(qty, 5)
if has_keys:
order = exchange.create_market_order(SYMBOL, side, qty)
return f"TESTNET {side.upper()} {qty} {SYMBOL} @ ~${price:,.2f} (id={order.get('id')})"
return f"SIMULATED TESTNET {side.upper()} {qty} {SYMBOL} @ ${price:,.2f}"
def trading_orchestrator_loop() -> None:
exchange, has_keys = create_testnet_exchange()
mode_label = "BINANCE TESTNET (LIVE KEYS)" if has_keys else "BINANCE TESTNET (SIMULATED)"
with state_lock:
bot_state["execution_mode"] = mode_label
add_event(f"Booting Capstone AI Bot in {mode_label} mode.")
# Initial bootstrap: fetch candles & load/train LightGBM bundle
candles = fetch_ohlcv_df(exchange, limit=300)
bundle = load_or_train_model(candles)
model = bundle["model"]
with state_lock:
add_event(f"LightGBM model ready ({MODEL_PATH.name}). Entering main loop.")
while not stop_event.is_set():
with state_lock:
status = bot_state["status"]
daily_pnl = float(bot_state["daily_pnl_usdt"])
position: Optional[Dict[str, float]] = bot_state["position"]
if status == "RUNNING":
try:
live_df = fetch_ohlcv_df(exchange, limit=120)
live_price = float(live_df.iloc[-1]["close"])
# Gate 1: Shared feature engine (drops unclosed candle)
feat_df = build_features(live_df, drop_unclosed_last_candle=True)
latest_row = feat_df.iloc[-1]
X_live = feat_df.iloc[[-1]][FEATURE_COLUMNS]
# Gate 2: Crash filter
crash_ok, crash_msg = check_crash_filter(latest_row)
# Gate 3: Market mood detector
mood = detect_market_mood(latest_row)
# Gate 4: LightGBM prediction
prob_up = float(model.predict_proba(X_live)[0][1])
decision = "HOLD"
# Gate 5: Risk Manager — manage open position exits first
if position is not None:
entry = position["entry_price"]
qty = position["qty"]
pnl_pct = (live_price - entry) / entry
if not crash_ok or pnl_pct <= -STOP_LOSS_PCT or pnl_pct >= TAKE_PROFIT_PCT:
reason = (
"CRASH EXIT" if not crash_ok
else "STOP LOSS" if pnl_pct <= -STOP_LOSS_PCT
else "TAKE PROFIT"
)
fill_msg = execute_testnet_order(exchange, has_keys, "sell", qty, live_price)
realized = (live_price - entry) * qty
with state_lock:
bot_state["daily_pnl_usdt"] = round(daily_pnl + realized, 2)
bot_state["position"] = None
decision = f"EXITED ({reason}, PnL ${realized:+.2f})"
add_event(f"{reason}: {fill_msg} | PnL ${realized:+.2f}")
else:
decision = f"HOLDING LONG ({pnl_pct*100:+.2f}%)"
# Gate 5b: Risk Manager — check new entry conditions
elif daily_pnl <= -MAX_DAILY_LOSS_USDT:
decision = "BLOCKED (Daily Loss Limit Reached)"
elif not crash_ok:
decision = f"BLOCKED ({crash_msg})"
elif mood == "BEARISH":
decision = "SKIPPED (Bearish Market Mood)"
elif prob_up >= AI_BUY_THRESHOLD:
qty = POSITION_SIZE_USDT / live_price
fill_msg = execute_testnet_order(exchange, has_keys, "buy", qty, live_price)
with state_lock:
bot_state["position"] = {"qty": round(qty, 5), "entry_price": live_price}
decision = f"BOUGHT (AI {prob_up*100:.1f}% | {mood})"
add_event(f"ENTRY: {fill_msg} | AI={prob_up*100:.1f}% | Mood={mood}")
else:
decision = f"WAIT (AI {prob_up*100:.1f}% < {AI_BUY_THRESHOLD*100:.0f}%)"
with state_lock:
bot_state["last_price"] = round(live_price, 2)
bot_state["market_mood"] = mood
bot_state["crash_status"] = crash_msg
bot_state["ai_prob_up"] = round(prob_up, 4)
bot_state["last_decision"] = decision
bot_state["last_updated"] = datetime.now(timezone.utc).strftime(
"%Y-%m-%d %H:%M:%S UTC"
)
except Exception as exc:
with state_lock:
add_event(f"Loop warning: {exc}")
stop_event.wait(timeout=POLL_SECONDS)
# ==============================================================================
# 7. LOCAL-ONLY FASTAPI DASHBOARD (127.0.0.1:8000)
# ==============================================================================
@asynccontextmanager
async def lifespan(_app: FastAPI):
worker = threading.Thread(target=trading_orchestrator_loop, daemon=True)
worker.start()
yield
stop_event.set()
worker.join(timeout=3.0)
app = FastAPI(title="Bitfoster Capstone AI Trading Bot", lifespan=lifespan)
class ControlRequest(BaseModel):
action: str
@app.get("/api/status")
def api_status() -> Dict[str, Any]:
with state_lock:
return {**bot_state, "events": list(bot_state["events"])}
@app.post("/api/control")
def api_control(req: ControlRequest) -> Dict[str, Any]:
action = req.action.lower().strip()
with state_lock:
if action == "start":
bot_state["status"] = "RUNNING"
add_event("Dashboard: Bot RESUMED.")
elif action == "pause":
bot_state["status"] = "PAUSED"
add_event("Dashboard: Bot PAUSED.")
elif action == "emergency_stop":
bot_state["status"] = "EMERGENCY_STOPPED"
bot_state["position"] = None
add_event("Dashboard: EMERGENCY STOP activated.")
return {"status": bot_state["status"]}
HTML_PAGE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Capstone AI Trading Bot</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0f172a; color: #e2e8f0; margin: 0; padding: 24px; }
.wrap { max-width: 920px; margin: 0 auto; }
.note { background: #1e293b; border-left: 4px solid #38bdf8; padding: 12px 16px; border-radius: 6px; margin-bottom: 18px; font-size: 14px; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; margin-bottom: 18px; }
.card { background: #1e293b; padding: 14px; border-radius: 10px; border: 1px solid #334155; }
.k { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; }
.v { font-size: 20px; font-weight: 700; margin-top: 6px; }
.btns { display: flex; gap: 10px; margin-bottom: 18px; }
button { padding: 10px 16px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
.start { background: #22c55e; color: #052e16; }
.pause { background: #f59e0b; color: #451a03; }
.stop { background: #ef4444; color: #ffffff; }
.log { background: #020617; border: 1px solid #334155; border-radius: 10px; padding: 14px; font-family: monospace; font-size: 13px; line-height: 1.6; min-height: 200px; }
</style>
</head>
<body>
<div class="wrap">
<h1>Capstone AI-Filtered Trading Bot</h1>
<div class="note">
Mode: <strong id="mode">--</strong> • Bound strictly to <code>127.0.0.1:8000</code> (local only) • Last decision: <strong id="decision">--</strong>
</div>
<div class="grid">
<div class="card"><div class="k">Status</div><div class="v" id="status">--</div></div>
<div class="card"><div class="k">BTC/USDT</div><div class="v" id="price">--</div></div>
<div class="card"><div class="k">Crash Filter</div><div class="v" id="crash">--</div></div>
<div class="card"><div class="k">Market Mood</div><div class="v" id="mood">--</div></div>
<div class="card"><div class="k">LightGBM Prob Up</div><div class="v" id="prob">--</div></div>
<div class="card"><div class="k">Daily PnL</div><div class="v" id="pnl">--</div></div>
</div>
<div class="btns">
<button class="start" onclick="ctrl('start')">Resume Bot</button>
<button class="pause" onclick="ctrl('pause')">Pause Bot</button>
<button class="stop" onclick="ctrl('emergency_stop')">Emergency Stop</button>
</div>
<h3>Decision & Execution Feed <small style="color:#94a3b8;">(<span id="ts">--</span>)</small></h3>
<div class="log" id="events">Booting...</div>
</div>
<script>
async function poll() {
const r = await fetch('/api/status');
const d = await r.json();
document.getElementById('mode').textContent = d.execution_mode;
document.getElementById('decision').textContent = d.last_decision;
document.getElementById('status').textContent = d.status;
document.getElementById('price').textContent = '$' + Number(d.last_price).toLocaleString();
document.getElementById('crash').textContent = d.crash_status;
document.getElementById('mood').textContent = d.market_mood;
document.getElementById('prob').textContent = (d.ai_prob_up * 100).toFixed(1) + '%';
document.getElementById('pnl').textContent = '$' + Number(d.daily_pnl_usdt).toFixed(2);
document.getElementById('ts').textContent = d.last_updated;
document.getElementById('events').innerHTML = d.events.join('<br/>') || 'No events yet.';
}
async function ctrl(action) {
await fetch('/api/control', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action })
});
poll();
}
poll();
setInterval(poll, 2000);
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
def index() -> str:
return HTML_PAGE
if __name__ == "__main__":
print("Launching Capstone AI Trading Bot Dashboard on http://127.0.0.1:8000 ...")
# Always bind strictly to 127.0.0.1 so controls stay private to your machine!
uvicorn.run(app, host="127.0.0.1", port=8000)
Launch your capstone bot:
python capstone_ai_bot.py
Open http://127.0.0.1:8000 in your browser to watch all five decision gates evaluate live Binance Testnet candles in real time.
Expected Terminal Output
Launching Capstone AI Trading Bot Dashboard on http://127.0.0.1:8000 ...
INFO: Started server process [51042]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:56104 - "GET / HTTP/1.1" 200 OK
INFO: 127.0.0.1:56104 - "GET /api/status HTTP/1.1" 200 OK
And inside the browser Event Feed on http://127.0.0.1:8000:
[11:50:16 UTC] ENTRY: SIMULATED TESTNET BUY 0.00531 BTC/USDT @ $94,180.50 | AI=61.4% | Mood=BULLISH
[11:50:01 UTC] LightGBM model ready (capstone_lgbm.joblib). Entering main loop.
[11:49:58 UTC] Booting Capstone AI Bot in BINANCE TESTNET (SIMULATED) mode.
Common Beginner Mistake: Letting an AI model trade without a separate crash filter or daily loss limit because "the model already sees volatility as a feature." Tree-based models like LightGBM cannot extrapolate well into rare, extreme market crashes that barely appeared in training data. Always keep deterministic hard-coded risk rules (crash halts, stop-losses, and daily drawdown limits) outside the machine learning model so they can override it unconditionally.
Study & Practice Recap
- Defense-in-depth beats any single model: Combining a shared feature engine, crash filter, mood detector, LightGBM classifier, and risk manager makes your bot transparent and safer to debug.
- Hard rules always outrank AI probabilities: Your crash filter, stop-loss, and daily loss cap can veto or close positions regardless of how confident the model looks.
- Safe local operations: Enforcing
set_sandbox_mode(True)for Binance Testnet andhost="127.0.0.1"for FastAPI keeps both your funds and your control panel protected while you learn.
Tiny Hands-On Exercise: Lower AI_BUY_THRESHOLD from 0.58 to 0.51 in capstone_ai_bot.py, run the bot on Binance Testnet for 5 minutes, and watch the dashboard event feed. Then click Emergency Stop and verify that the bot immediately halts new entries while keeping the dashboard responsive.