HomePhase 5: Live AI BotLesson 23
Lesson 23 of 24Phase 5: Live AI BotIntermediate

Building a Simple Web Dashboard for Your Bot

Build a clean, local-only FastAPI web dashboard bound to 127.0.0.1 so you can monitor positions, inspect AI signals, and stop your Testnet bot visually.

Bitfoster Team
December 3, 2026
12 Min Read
lesson-23-bot-web-dashboard/
Building a Simple Web Dashboard for Your Bot

Hands-On Deliverable

A live browser control panel to monitor and control your bot visually.

Educational Disclaimer & Safety First: This project is for learning software and trading-bot architecture only—it is not financial advice. Always connect your bot exclusively to Binance Testnet, and always bind your FastAPI dashboard to 127.0.0.1 (localhost). Never bind an unauthenticated trading dashboard to 0.0.0.0, or anyone on your Wi-Fi network—or the public internet—could click your Start / Stop Bot buttons!

Why a Browser Dashboard Beats Staring at Scrolling Terminal Logs

When your bot runs in a plain terminal window, it is easy to miss critical information:

  • Is the bot currently paused, running, or stuck on an API error?
  • What is the latest AI confidence score and market mood?
  • How much simulated Testnet USDT balance is left, and what was the last trade?
  • How do you cleanly pause new entries without slamming Ctrl+C in the middle of an open order?

A lightweight web dashboard solves all four problems in under 200 lines of Python.

Why We Choose FastAPI + Local-Only Polling (127.0.0.1)

Before writing code, let's understand why this exact architecture is ideal for beginners:

  1. FastAPI is built for Python: You don't need Node.js, React, Webpack, or a separate frontend build step. FastAPI serves both your JSON API (/api/status, /api/control) and a clean HTML control panel (/) from a single Python file.
  2. Thread-safe shared state: Your trading loop runs in a background thread while FastAPI handles browser clicks. Protecting the shared bot_state dictionary with a threading.Lock() prevents race conditions when the bot updates prices at the exact millisecond you click Pause.
  3. Strict 127.0.0.1 binding: Passing host="127.0.0.1" to uvicorn tells your operating system to accept browser connections only from your own computer. Even if your laptop is on coffee-shop Wi-Fi, nobody else can open your dashboard or trigger your Emergency Stop.
  4. Simple 2-second polling (fetch('/api/status')): Instead of fragile WebSocket reconnect logic, the browser refreshes JSON state every 2 seconds—simple to read, simple to debug, and rock-solid.
Your Browser (http://127.0.0.1:8000)
   ├── GET  /             ──► HTML Control Panel (Status Cards + Buttons)
   ├── GET  /api/status   ──► Live JSON Snapshot (every 2 seconds)
   └── POST /api/control  ──► Pause / Resume / Emergency Stop
                                      │
                             [ threading.Lock() ]
                                      │
                       Background Binance Testnet Bot Loop

Prerequisites

Install FastAPI, Uvicorn (the ASGI web server), and CCXT:

pip install fastapi uvicorn ccxt

Complete Runnable Code (dashboard.py)

Create a file called dashboard.py. It fetches real live prices from Binance Testnet (set_sandbox_mode(True)) in a background worker thread and exposes a live control panel at http://127.0.0.1:8000.

# dashboard.py
"""
Lesson 23: Local-Only FastAPI Web Dashboard for Your Trading Bot
Binds strictly to 127.0.0.1:8000 so controls are never exposed to the public internet.
"""

from contextlib import asynccontextmanager
from datetime import datetime, timezone
import threading
import time
from typing import Any, Dict, List

import ccxt
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
import uvicorn

# Thread-safe shared state between the background bot loop and FastAPI endpoints
state_lock = threading.Lock()
stop_event = threading.Event()

bot_state: Dict[str, Any] = {
    "mode": "BINANCE TESTNET (SANDBOX)",
    "symbol": "BTC/USDT",
    "status": "RUNNING",          # RUNNING | PAUSED | EMERGENCY_STOPPED
    "last_price": 0.0,
    "ai_confidence": 0.50,        # Simulated 0.0 - 1.0 score (wired to LightGBM in Lesson 24)
    "market_mood": "NEUTRAL",
    "testnet_usdt_balance": 10000.00,
    "open_position": "FLAT",
    "last_updated": "Starting...",
    "recent_events": [],
}


def log_event(message: str) -> None:
    """Append a timestamped event to the dashboard activity feed (caller holds or acquires lock)."""
    ts = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")
    entry = f"[{ts}] {message}"
    events: List[str] = bot_state["recent_events"]
    events.insert(0, entry)
    del events[12:]  # Keep the 12 most recent events


def bot_worker_loop() -> None:
    """Background worker polling Binance Testnet ticker prices safely."""
    exchange = ccxt.binance({"enableRateLimit": True})
    exchange.set_sandbox_mode(True)  # Always enforce Binance Testnet!

    with state_lock:
        log_event("Connected to Binance Testnet public feed.")

    while not stop_event.is_set():
        with state_lock:
            current_status = bot_state["status"]
            symbol = bot_state["symbol"]

        if current_status == "RUNNING":
            try:
                ticker = exchange.fetch_ticker(symbol)
                price = float(ticker["last"])
                change_pct = float(ticker.get("percentage") or 0.0)

                # Simple mood label based on 24h Testnet change (upgraded in Lesson 24)
                if change_pct > 1.0:
                    mood = "BULLISH"
                elif change_pct < -1.0:
                    mood = "DEFENSIVE"
                else:
                    mood = "NEUTRAL"

                # Placeholder confidence score for visual testing
                confidence = max(0.05, min(0.95, 0.50 + (change_pct / 20.0)))

                with state_lock:
                    bot_state["last_price"] = round(price, 2)
                    bot_state["market_mood"] = mood
                    bot_state["ai_confidence"] = round(confidence, 4)
                    bot_state["last_updated"] = datetime.now(timezone.utc).strftime(
                        "%Y-%m-%d %H:%M:%S UTC"
                    )
                    log_event(f"Tick {symbol} = ${price:,.2f} | Mood: {mood}")
            except Exception as exc:
                with state_lock:
                    log_event(f"Testnet poll warning: {exc}")

        # Sleep in short increments so shutdown is instant
        stop_event.wait(timeout=5.0)


@asynccontextmanager
async def lifespan(_app: FastAPI):
    """Start the background bot thread when FastAPI boots, and stop cleanly on exit."""
    worker = threading.Thread(target=bot_worker_loop, daemon=True)
    worker.start()
    yield
    stop_event.set()
    worker.join(timeout=3.0)


app = FastAPI(title="Bitfoster Local Bot Dashboard", lifespan=lifespan)


class ControlCommand(BaseModel):
    action: str  # "start" | "pause" | "emergency_stop"


@app.get("/api/status")
def get_status() -> Dict[str, Any]:
    """Return a thread-safe snapshot of the bot's live state."""
    with state_lock:
        return {
            **bot_state,
            "recent_events": list(bot_state["recent_events"]),
        }


@app.post("/api/control")
def control_bot(cmd: ControlCommand) -> Dict[str, Any]:
    """Handle Start, Pause, and Emergency Stop commands from the local browser."""
    action = cmd.action.lower().strip()
    with state_lock:
        if action == "start":
            bot_state["status"] = "RUNNING"
            log_event("User clicked RESUME BOT from local dashboard.")
        elif action == "pause":
            bot_state["status"] = "PAUSED"
            log_event("User clicked PAUSE BOT from local dashboard.")
        elif action == "emergency_stop":
            bot_state["status"] = "EMERGENCY_STOPPED"
            bot_state["open_position"] = "FLAT (STOPPED)"
            log_event("EMERGENCY STOP triggered! New entries halted.")
        else:
            return {"ok": False, "error": f"Unknown action: {action}"}
        return {"ok": True, "status": bot_state["status"]}


DASHBOARD_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Bitfoster Local Bot Dashboard</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0f172a; color: #e2e8f0; margin: 0; padding: 24px; }
    .container { max-width: 860px; margin: 0 auto; }
    .banner { background: #1e293b; border-left: 4px solid #38bdf8; padding: 12px 16px; border-radius: 6px; margin-bottom: 20px; font-size: 14px; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-bottom: 20px; }
    .card { background: #1e293b; padding: 16px; border-radius: 10px; border: 1px solid #334155; }
    .label { font-size: 12px; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; }
    .value { font-size: 22px; font-weight: 700; margin-top: 6px; }
    .controls { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
    button { padding: 10px 18px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; font-size: 14px; }
    .btn-start { background: #22c55e; color: #052e16; }
    .btn-pause { background: #f59e0b; color: #451a03; }
    .btn-stop  { background: #ef4444; color: #ffffff; }
    .log-box { background: #020617; border: 1px solid #334155; border-radius: 10px; padding: 14px; font-family: monospace; font-size: 13px; line-height: 1.6; min-height: 180px; }
  </style>
</head>
<body>
  <div class="container">
    <h1>Bitfoster AI Bot Control Panel</h1>
    <div class="banner">
      <strong>Safety Check:</strong> Bound strictly to <code>127.0.0.1</code> (local machine only) &bull; Connected to <strong id="mode">BINANCE TESTNET</strong>.
    </div>

    <div class="grid">
      <div class="card"><div class="label">Bot Status</div><div class="value" id="status">--</div></div>
      <div class="card"><div class="label">BTC/USDT Price</div><div class="value" id="price">--</div></div>
      <div class="card"><div class="label">Market Mood</div><div class="value" id="mood">--</div></div>
      <div class="card"><div class="label">AI Confidence</div><div class="value" id="conf">--</div></div>
      <div class="card"><div class="label">Testnet Balance</div><div class="value" id="bal">--</div></div>
      <div class="card"><div class="label">Position</div><div class="value" id="pos">--</div></div>
    </div>

    <div class="controls">
      <button class="btn-start" onclick="sendControl('start')">Resume Bot</button>
      <button class="btn-pause" onclick="sendControl('pause')">Pause Bot</button>
      <button class="btn-stop" onclick="sendControl('emergency_stop')">Emergency Stop</button>
    </div>

    <h3>Live Event Log <small style="color:#94a3b8;font-weight:400;">(Updated: <span id="updated">--</span>)</small></h3>
    <div class="log-box" id="events">Waiting for Testnet data...</div>
  </div>

  <script>
    async function refreshStatus() {
      const res = await fetch('/api/status');
      const data = await res.json();
      document.getElementById('mode').textContent = data.mode;
      document.getElementById('status').textContent = data.status;
      document.getElementById('price').textContent = '$' + Number(data.last_price).toLocaleString();
      document.getElementById('mood').textContent = data.market_mood;
      document.getElementById('conf').textContent = (data.ai_confidence * 100).toFixed(1) + '%';
      document.getElementById('bal').textContent = '$' + Number(data.testnet_usdt_balance).toLocaleString();
      document.getElementById('pos').textContent = data.open_position;
      document.getElementById('updated').textContent = data.last_updated;
      document.getElementById('events').innerHTML = data.recent_events.join('<br/>') || 'No events yet.';
    }

    async function sendControl(action) {
      await fetch('/api/control', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action })
      });
      refreshStatus();
    }

    refreshStatus();
    setInterval(refreshStatus, 2000);
  </script>
</body>
</html>
"""


@app.get("/", response_class=HTMLResponse)
def serve_dashboard() -> str:
    """Serve the local browser control panel."""
    return DASHBOARD_HTML


if __name__ == "__main__":
    print("Starting Bitfoster Local Dashboard at http://127.0.0.1:8000 ...")
    # CRITICAL SAFETY SETTING: host="127.0.0.1" prevents external network access!
    uvicorn.run(app, host="127.0.0.1", port=8000)

Run the dashboard from your terminal:

python dashboard.py

Then open your browser and visit http://127.0.0.1:8000. Try clicking Pause Bot, Resume Bot, and Emergency Stop and watch the status card and event log update immediately.


Expected Terminal Output

Starting Bitfoster Local Dashboard at http://127.0.0.1:8000 ...
INFO:     Started server process [48210]
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:54312 - "GET / HTTP/1.1" 200 OK
INFO:     127.0.0.1:54312 - "GET /api/status HTTP/1.1" 200 OK
INFO:     127.0.0.1:54312 - "POST /api/control HTTP/1.1" 200 OK

Common Beginner Mistake: Running uvicorn.run(app, host="0.0.0.0", port=8000) after copying a deployment snippet from Stack Overflow. Binding to 0.0.0.0 exposes your unauthenticated Resume and Emergency Stop endpoints to every device on your local network (and the entire internet if you run on a cloud VPS with open firewall ports). Always bind personal bot dashboards strictly to 127.0.0.1, and if you ever access a remote server, use an encrypted SSH tunnel (ssh -L 8000:127.0.0.1:8000 user@server) instead of opening port 8000 publicly.


Study & Practice Recap

  • FastAPI handles UI + API in one file: You can serve an interactive browser control panel without introducing a separate JavaScript build toolchain.
  • Lock shared state: Wrapping reads and writes to bot_state in threading.Lock() prevents corrupted numbers when the trading thread and web server run simultaneously.
  • Local-only by default: Keeping host="127.0.0.1" ensures only your own computer can view your Testnet stats or trigger your bot's control buttons.

Tiny Hands-On Exercise: Add a fourth card to DASHBOARD_HTML called Poll Count that increments inside bot_worker_loop() every time a new Binance Testnet ticker is fetched, and confirm it ticks up automatically in your browser every 5 seconds.

Topics:#AI Bot#FastAPI#Dashboard#Python#Binance Testnet