DEV Community

Market Masters
Market Masters

Posted on

Build a Real-Time Crypto Trading Dashboard: React + Python API Tutorial

Build a Real-Time Crypto Trading Dashboard: React + Python API Tutorial

You've seen the price charts. BTC pumps 10% in an hour, then dumps. Retail traders chase, institutions front-run. What if you had a dashboard that pulls live prices, runs basic technical analysis, and alerts on breakouts? No $10k setup, just code.

This tutorial builds one using React for the frontend, Python for API calls and TA, and the Market Masters API (free tier available). Expect a working prototype in 30 minutes. Focus: real-time updates via WebSockets (simulated), RSI/MACD signals, portfolio tracker stub.

SEO keywords: React, Python, trading API, crypto dashboard tutorial, real-time prices, technical analysis.

Why This Stack?

  • React: Handles state, charts (Recharts), live updates without page reloads. Tradeoff: bundle size vs. instant feedback.
  • Python (FastAPI): Server for API proxy + TA (TA-Lib). Why proxy? Free tiers rate-limit; batch requests here.
  • Market Masters API: 2500+ cryptos, real-time screeners. Free tier: basic prices/alerts. Docs: marketmasters.ai/api.

Gotchas: CORS (proxy fixes), API keys (env vars), WebSocket reconnects.

Step 1: Python Backend (FastAPI + TA-Lib)

Install deps:

pip install fastapi uvicorn ta-lib requests python-dotenv
Enter fullscreen mode Exit fullscreen mode

backend/main.py:

import os
from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware
import requests
import talib
import numpy as np
from dotenv import load_dotenv

load_dotenv()
MM_API_KEY = os.getenv('MM_API_KEY')

app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])

@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        # Simulate live prices (replace with real MM WS)
        data = {'btc': np.random.uniform(60_000, 70_000), 'eth': np.random.uniform(3_000, 3_500)}
        await websocket.send_json(data)
        await asyncio.sleep(5)

@app.get('/prices/{symbol}')
async def get_prices(symbol: str):
    url = f'https://api.marketmasters.ai/v1/crypto/{symbol}?key={MM_API_KEY}'
    resp = requests.get(url).json()
    closes = np.array(resp['closes'][-14:], dtype=float)  # Last 14
    rsi = talib.RSI(closes)
    macd = talib.MACD(closes)
    return {'prices': resp['prices'], 'rsi': rsi[-1], 'macd': macd[0][-1], 'signal': 'buy' if rsi[-1] < 30 else 'sell' if rsi[-1] > 70 else 'hold'}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8000)
Enter fullscreen mode Exit fullscreen mode

Run: uvicorn main:app --reload. Test: curl localhost:8000/prices/BTC.

Step 2: React Frontend

npx create-react-app dashboard && cd dashboard && npm i recharts axios.

src/App.js:

import React, { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, ResponsiveContainer, Tooltip } from 'recharts';
import axios from 'axios';

const App = () => {
  const [data, setData] = useState({});
  const [prices, setPrices] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await axios.get('http://localhost:8000/prices/BTC');
      setData(res.data);
      setPrices(prev => [...prev.slice(-20), {time: new Date(), price: res.data.prices[-1]}]);
    };
    fetchData();
    const interval = setInterval(fetchData, 10000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h1>Crypto Trading Dashboard</h1>
      <p>RSI: {data.rsi?.toFixed(2)} | Signal: {data.signal}</p>
      <ResponsiveContainer width="100%" height={400}>
        <LineChart data={prices}>
          <Line type="monotone" dataKey="price" stroke="#8884d8" />
          <XAxis dataKey="time" />
          <YAxis />
          <Tooltip />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

npm start. Open localhost:3000. Live chart + signals.

Portfolio Tracker Stub

Add to Python:

@app.post('/portfolio')
async def track_portfolio(portfolio: dict):
    # Stub: calc value, risk
    return {'total': sum(v * get_prices(k)['prices'][-1] for k,v in portfolio.items()), 'risk': 'medium'}
Enter fullscreen mode Exit fullscreen mode

React POST call similar.

Tradeoffs & Next Steps

  • Polling vs WS: Polling simple; WS scales (use Socket.io).
  • TA-Lib: Fast C++; pandas-ta alternative for pure Py.
  • Prod: Docker, Redis cache, auth.

Fork this on GitHub, tweak for stocks/ETFs via MM API.

CTA: Get live data free at Market Masters (30-day Premium trial, no CC). API docs: marketmasters.ai/api. Build smarter, trade better.

Top comments (0)