Skip to content

vineetkia/TradeHub

 
 

Repository files navigation

CMPE-272 Real-time Scalable Trading Platform

A professional-grade web-based trading application that provides real-time stock and cryptocurrency market data, portfolio management, account analytics, and secure user authentication.

TradeHub Node TypeScript Python

Quick Start

Get TradeHub running in under 5 minutes:

# 1. Install dependencies
npm install

# 2. Set up environment variables
cp .env.template .env
# Edit .env with your DATABASE_URL and JWT_SECRET

# 3. Create PostgreSQL database
psql -U postgres -c 'CREATE DATABASE "tradePlatform";'

# 4. Push database schema
npm run db:push

# 5. Start Price Stream Service (Terminal 1)
cd microservices/price-stream-service
pip install -r requirements.txt
python main.py

# 6. Optional: Start News Feed Service (Terminal 1 or 3)
cd ../news-feed-service
pip install -r requirements.txt
python main.py

# 7. Optional: Start PnL Report Service (Terminal 1 or 4)
cd ../pnl-report-service
cp .env.template .env
# Fill .env with SMTP and tokens (see below)
pip install -r requirements.txt
python main.py

# 8. Start main application (Terminal 2)
cd ../..  # Back to project root
npm run dev

# 9. Open browser to http://localhost:3000

That's it! You should see the TradeHub login/register page. Create an account to start trading with $10,000 virtual balance.


Features

  • Real-time Market Data: Live stock quotes and cryptocurrency prices via Price Stream microservice
  • Portfolio Management: Track your investments with $10,000 starting balance
  • Trading Execution: Buy/sell stocks and cryptocurrencies with real-time pricing
  • P&L Analytics: Interactive charts showing 24-hour and 30-day performance
  • Secure Authentication: JWT-based auth with optional two-factor authentication (2FA)
  • Role-Based Access Control: User and admin roles with different permissions
  • WebSocket Updates: Real-time price updates (1-10 second intervals)
  • Market Analysis: View top gainers, losers, and most active securities
  • Responsive Design: Beautiful glassmorphism UI with dark/light mode

Tech Stack

Frontend

  • React 18 with TypeScript
  • Vite - Fast build tool with HMR
  • Tailwind CSS - Utility-first styling
  • Radix UI - Accessible component primitives
  • React Query - Server state management
  • Recharts - Interactive data visualization
  • Wouter - Lightweight routing

Backend

  • Express.js with TypeScript
  • PostgreSQL - Relational database
  • Drizzle ORM - Type-safe database operations
  • JWT - Stateless authentication
  • WebSocket (ws) - Real-time communication
  • bcrypt - Password hashing
  • Speakeasy - TOTP 2FA implementation

Microservices

  • Price Stream Service (Python/FastAPI)

    • Real-time price streaming from TradingView
    • No API key required
    • No rate limits
    • WebSocket-based architecture
    • Supports 20+ symbols (stocks + crypto)
  • News Feed Service (Python/FastAPI)

    • Aggregates market and financial news from providers (e.g., NewsAPI)
    • Token-protected via x-news-service-token when configured
    • REST endpoint: GET /api/news/latest
    • Default port: 8001
  • PnL Report Service (Python/FastAPI)

    • Generates daily Profit & Loss PDFs from portfolio, holdings, and trades
    • Protected via x-pnl-service-token; returns application/pdf
    • REST endpoint: POST /api/reports/pnl/daily.pdf
    • Optional email scheduler (daily send) using SMTP envs
    • Default port: 8002

TradingView Price Chart

  • Integrated TradingView Advanced Charts in the frontend

  • Symbol mapping for stocks and crypto (e.g., NASDAQ:AAPL, BINANCE:BTCUSDT)

  • Theme sync with dark/light mode

  • Timeframe controls: 1D, 1M, 3M, 1Y, ALL (no 1W)

  • Implementation: client/src/components/price-chart.tsx:13-19, widget config at client/src/components/price-chart.tsx:112-123

  • Role Management Service (Python/FastAPI)

    • Centralizes user role lifecycle: init, approve/reject, change role, audit
    • Admin-protected via x-role-service-token (ROLE_SERVICE_ADMIN_TOKEN env)
    • Key endpoints: POST /api/roles/users, GET /api/roles/users/{userId}, POST /api/roles/users/{userId}/approve|reject|role, GET /api/roles/audit
    • Rate-limited (60 req/min per IP)
    • Default port: 7001

External APIs

  • TradingView API - Real-time market data via Price Stream Service

Prerequisites

Before setting up the project, ensure you have the following installed:

Required

  • Node.js (v18 or higher) - Download
  • PostgreSQL (v12 or higher) - Download
  • Python (v3.9 or higher) - Download for Price Stream Service
  • npm or yarn - Comes with Node.js
  • Git - Download

Note

The Price Stream Service microservice is required for real-time market data. Without it running, price data will not be available.


Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd CMPE-272-Project

2. Install Dependencies

npm install

This will install all required dependencies (~530 packages).

3. Set Up PostgreSQL Database

Create Database

Open your terminal and connect to PostgreSQL:

psql -U postgres

Create a new database for the project:

CREATE DATABASE "tradePlatform";

Verify the database was created:

\l

Exit psql:

\q

Alternative: One-line command

psql -U postgres -c 'CREATE DATABASE "tradePlatform";'

4. Configure Environment Variables

Create a .env file in the project root directory:

touch .env

Add the following configuration to .env:

# Database Configuration
# Format: postgresql://username:password@localhost:5432/database_name
DATABASE_URL=postgresql://postgres:your_password@localhost:5432/tradePlatform

# JWT Secret Key (for authentication tokens)
# Generate a secure random string (minimum 32 characters)
JWT_SECRET=your-super-secret-jwt-key-change-this-to-something-random-and-secure-min-32-chars

# Environment
NODE_ENV=development

# Server Port (default: 3000)
PORT=3000

Configuration Details

DATABASE_URL:

  • Replace postgres with your PostgreSQL username
  • Replace your_password with your PostgreSQL password
  • Replace tradePlatform with your database name (or keep it)
  • Default port for PostgreSQL is 5432

JWT_SECRET:

  • Generate a secure random string using:
    node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

PORT:

  • Default is 3000
  • Note: Port 5000 may conflict with macOS AirPlay Receiver

5. Push Database Schema

Run the database migration to create all required tables:

npm run db:push

This will create the following tables:

  • users - User authentication and profiles
  • portfolios - User portfolio balances
  • holdings - Stock and crypto positions
  • trades - Transaction history
  • pnl_snapshots - Time-series profit/loss data

Expected output:

✓ Pulling schema from database...
✓ Changes applied

Running the Project

The TradeHub platform consists of three core components and two optional microservices:

  1. Price Stream Service (Python microservice) - Port 8000
  2. Backend Server (Express.js) - Port 3000
  3. Frontend (Vite/React) - Served by backend on port 3000
  4. News Feed Service (Python microservice) - Port 8001 (optional)
  5. PnL Report Service (Python microservice) - Port 8002 (optional)

Option 1: Run All Components (Recommended)

Terminal 1 - Start Price Stream Microservice:

# Navigate to microservice directory
cd microservices/price-stream-service

# Install Python dependencies (first time only)
pip install -r requirements.txt

# Start the microservice
python main.py

You should see:

INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000

Terminal 2 - Start Main Application (Backend + Frontend):

# From project root directory
npm run dev

You should see:

serving on port 3000
✅ Connected to price-stream-service
📡 Subscribed to 20 symbols on price-stream-service

The application will be available at:

Option 2: Run Without Microservice

⚠️ Warning: The main application requires the Price Stream Service microservice to function properly. Without it, no real-time price data will be available.

If the microservice is not running, you'll see connection errors in the console, and the trading functionality will be limited.

Option 3: Docker Compose (Microservice Only)

Run the Price Stream Service using Docker:

cd microservices/price-stream-service
docker-compose up

Microservices Setup (Any Machine)

News Feed Service (Port 8001):

cd microservices/news-feed-service
cp .env.template .env  # if present; otherwise set env via shell
# Minimal envs:
# NEWS_PROVIDERS=newsapi
# NEWSAPI_KEY=<your_newsapi_key>
# NEWS_SERVICE_TOKEN=<shared_secret_optional>
pip install -r requirements.txt
python main.py

PnL Report Service (Port 8002):

cd microservices/pnl-report-service
cp .env.template .env
# Fill .env:
# PNL_REPORT_SERVICE_TOKEN=<shared_secret_optional>
# REPORT_SOURCE_URL=http://localhost:3000/api/portfolio
# REPORT_USER_JWT=<copy JWT cookie value after login>
# REPORT_RECIPIENT_EMAIL=<you@example.com>
# SMTP_HOST=<smtp.example.com>
# SMTP_PORT=587
# SMTP_USER=<smtp-username>
# SMTP_PASS=<smtp-password>
# PNL_REPORT_SEND_TIME=19:00
pip install -r requirements.txt
python main.py

Notes:

  • To obtain REPORT_USER_JWT, log in to the main app, open browser developer tools → Application/Storage → Cookies, and copy the JWT cookie value. Alternatively, call the login API and copy the Set-Cookie token.
  • Scheduler runs daily at PNL_REPORT_SEND_TIME when SMTP and recipient are configured.

Verifying Everything is Running

Check Price Stream Service:

curl http://localhost:8000/health

Expected response:

{
  "status": "healthy",
  "active_connections": 1,
  "active_streams": 20
}

Check Main Application:

curl http://localhost:3000/api/stocks/search?q=AAPL

Expected: JSON response with stock data

Check Frontend: Open browser to http://localhost:3000 - You should see the login/register page

Production Build

Build the project for production:

npm run build

This will:

  1. Build the frontend (Vite) → dist/public/
  2. Bundle the backend (esbuild) → dist/index.js

Start the production server:

npm start

Type Checking

Run TypeScript type checking without building:

npm run check

Using the Application

1. Register an Account

  1. Navigate to http://localhost:3000
  2. Click "Register" or go to /register
  3. Fill in your details:
    • Name
    • Email
    • Password (minimum 6 characters)
    • Optional: Enable 2FA (scan QR code with authenticator app)
  4. Click "Register"
  5. You'll be logged in with $10,000 starting balance

2. Start Trading

Buy Assets:

  1. Go to the Dashboard
  2. Click the "Buy/Sell" tab
  3. Search for a stock (e.g., "AAPL", "TSLA") or crypto (e.g., "BTC", "ETH")
  4. Select the asset from results
  5. Enter the quantity you want to buy
  6. Click "Buy [Symbol]"
  7. Your balance will update, and the position will appear in your portfolio

Sell Assets:

  1. Follow the same steps as buying
  2. Toggle to "Sell" mode
  3. Enter quantity to sell
  4. Click "Sell [Symbol]"

3. Monitor Your Portfolio

Portfolio Tab:

  • View all your holdings
  • See real-time prices and P&L for each position
  • Track total portfolio value

Analytics Tab:

  • Interactive P&L charts (24-hour and 30-day views)
  • See total value, cash balance, holdings value, and P&L breakdown
  • Auto-refreshes every 60 seconds

Market Movers Tab:

  • View top gainers, losers, and most active stocks/crypto
  • Real-time price updates

4. Admin Features (Admin Users Only)

Access the admin panel at /admin:

  • View all registered users
  • Suspend/unsuspend user accounts
  • Reset user 2FA
  • Delete user accounts

Supported Assets

Stocks (10)

  • AAPL - Apple Inc.
  • TSLA - Tesla, Inc.
  • GOOGL - Alphabet Inc.
  • MSFT - Microsoft Corporation
  • AMZN - Amazon.com, Inc.
  • META - Meta Platforms, Inc.
  • NVDA - NVIDIA Corporation
  • AMD - Advanced Micro Devices, Inc.
  • NFLX - Netflix, Inc.
  • DIS - The Walt Disney Company

Cryptocurrencies (10)

  • BTC - Bitcoin
  • ETH - Ethereum
  • BNB - Binance Coin
  • SOL - Solana
  • XRP - Ripple
  • ADA - Cardano
  • DOGE - Dogecoin
  • AVAX - Avalanche
  • DOT - Polkadot
  • MATIC - Polygon

Price Stream Microservice

The Price Stream Service is a standalone Python/FastAPI microservice that provides real-time price streaming for stocks and cryptocurrencies.

Why Use the Microservice?

Key Features:

  • No API Key Required - Uses TradingView's free WebSocket API
  • No Rate Limits - Unlimited price updates
  • Fast Updates - 1-3 second intervals for real-time data
  • Independent Scaling - Can run on separate server
  • Reliable - Auto-reconnection with exponential backoff
  • Live Crypto Prices - Real-time cryptocurrency prices from Binance
  • Stock Market Hours - Returns last price when market is closed, live prices during trading hours

Architecture

Main Platform → WebSocket → Price Stream Service → TradingView API
     ↓                              ↓
Backend (Port 3000)        FastAPI (Port 8000)
     ↓
Frontend (React)

Supported Symbols

Stocks (10): AAPL, TSLA, GOOGL, MSFT, AMZN, META, NVDA, AMD, NFLX, DIS Crypto (10): BTC, ETH, BNB, SOL, XRP, ADA, DOGE, AVAX, DOT, MATIC

Microservice Endpoints

  • ws://localhost:8000/ws - WebSocket endpoint for price streaming
  • GET /health - Health check with active streams info
  • GET /streams - Detailed stream information
  • GET / - Service documentation

Setting Up the Microservice

1. Navigate to microservice directory:

cd microservices/price-stream-service

2. Install Python dependencies:

pip install -r requirements.txt

Or using a virtual environment (recommended):

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Start the service:

python main.py

4. Verify it's running:

curl http://localhost:8000/health

WebSocket Protocol

Subscribe to symbols:

{
  "action": "bulk_subscribe",
  "symbols": [
    {"symbol": "BTC", "market": "crypto"},
    {"symbol": "AAPL", "market": "stock"}
  ]
}

Receive price updates:

{
  "symbol": "BTC",
  "symbol_id": "BINANCE:BTCUSDT",
  "price": 100500.50,
  "market": "crypto",
  "timestamp": "2025-11-04T12:00:00.000000"
}

Docker Deployment

Using Docker Compose:

cd microservices/price-stream-service
docker-compose up

Building manually:

docker build -t price-stream-service .
docker run -p 8000:8000 price-stream-service

Performance Metrics

  • Memory Usage: 50-100MB
  • CPU Usage: <5%
  • Latency: <1 second
  • Updates: 300+ per minute across all symbols
  • Concurrent Streams: 20+ symbols efficiently

Project Structure

CMPE-272-Project/
├── client/                     # Frontend React application
│   ├── src/
│   │   ├── components/         # React components
│   │   │   ├── ui/             # Base UI components (Radix wrappers)
│   │   │   ├── trade-panel.tsx
│   │   │   ├── portfolio-table.tsx
│   │   │   ├── pnl-chart.tsx
│   │   │   └── ...
│   │   ├── hooks/              # Custom React hooks
│   │   ├── lib/                # Utilities and configs
│   │   │   ├── auth-context.tsx
│   │   │   └── queryClient.ts
│   │   ├── pages/              # Page-level components
│   │   │   ├── dashboard.tsx
│   │   │   ├── login.tsx
│   │   │   └── ...
│   │   ├── App.tsx             # Main app component
│   │   └── main.tsx            # Entry point
│   └── public/                 # Static assets
│
├── server/                     # Backend Express application
│   ├── lib/                    # Server utilities
│   │   ├── auth.ts             # JWT, 2FA, password hashing
│   │   └── market-data.ts      # Market data utilities and asset definitions
│   ├── db.ts                   # Database connection
│   ├── index.ts                # Server entry point
│   ├── routes.ts               # API endpoints (945 lines)
│   ├── storage.ts              # Database operations (212 lines)
│   └── vite.ts                 # Vite integration
│
├── shared/                     # Shared TypeScript types
│   └── schema.ts               # Database schema (168 lines)
│
├── microservices/              # Independent microservices
│   └── price-stream-service/   # Python/FastAPI price streaming
│       ├── main.py             # FastAPI WebSocket server (326 lines)
│       ├── tradingview_manager.py  # TradingView integration (353 lines)
│       ├── requirements.txt    # Python dependencies
│       ├── Dockerfile          # Docker configuration
│       ├── docker-compose.yml  # Docker Compose setup
│       ├── test_client.py      # Python CLI test client
│       └── test_client.html    # Browser test interface
│
├── .env                        # Environment variables
├── .env.template               # Environment template
├── package.json                # Node.js dependencies
├── tsconfig.json               # TypeScript configuration
├── vite.config.ts              # Vite configuration
├── tailwind.config.ts          # Tailwind CSS configuration
├── drizzle.config.ts           # Database migrations config
├── documentation/PROJECT_CONTEXT.md  # Comprehensive project documentation
└── README.md                   # This file

API Endpoints

Authentication

  • POST /api/auth/register - Create new user
  • POST /api/auth/login - Login with credentials
  • POST /api/auth/logout - Clear session
  • GET /api/auth/me - Get current user
  • POST /api/auth/2fa/* - 2FA management

Portfolio

  • GET /api/portfolio - Get portfolio with holdings and trades
  • GET /api/portfolio/pnl/:period - Get P&L snapshots (24h/30d)

Trading

  • POST /api/trades - Execute buy/sell trade

Market Data

  • GET /api/stocks/search?q=<query> - Search assets
  • GET /api/stocks/:symbol - Get quote for symbol
  • GET /api/stocks/movers - Get market movers

Admin (Admin only)

  • GET /api/admin/users - Get all users
  • POST /api/admin/users/:id/suspend - Suspend user
  • POST /api/admin/users/:id/reset-2fa - Reset 2FA
  • DELETE /api/admin/users/:id - Delete user

User Settings

  • PUT /api/user/profile - Update profile
  • POST /api/user/change-password - Change password

Troubleshooting

Port Already in Use

Error: Error: listen EADDRINUSE: address already in use :::5000

Solution: Port 5000 is commonly used by macOS AirPlay Receiver. Change the port in .env:

PORT=3000

Database Connection Error

Error: database "tradePlatform" does not exist

Solution: Create the database using psql:

psql -U postgres -c 'CREATE DATABASE "tradePlatform";'

Environment Variables Not Loading

Error: DATABASE_URL must be set

Solution:

  1. Ensure .env file exists in the project root
  2. Verify dotenv is installed: npm install dotenv
  3. Check that import 'dotenv/config'; is at the top of server/index.ts

PostgreSQL Connection Failed

Error: connection to server on socket failed

Solution:

  1. Verify PostgreSQL is running:
    brew services list  # macOS
    sudo systemctl status postgresql  # Linux
  2. Start PostgreSQL if needed:
    brew services start postgresql  # macOS
    sudo systemctl start postgresql  # Linux
  3. Verify credentials in .env are correct

Price Data Not Available

Error: Price not available or Failed to get quote

Solution:

  1. Ensure the Price Stream Service microservice is running
  2. Check microservice health: curl http://localhost:8000/health
  3. Verify the backend is connected to the microservice (check logs for "✅ Connected to price-stream-service")
  4. Restart both services if needed

Build Errors

Error: TypeScript compilation errors

Solution: Run type checking to see specific errors:

npm run check

Microservice Connection Error

Error: Failed to connect to price-stream-service

Solution:

  1. Verify the microservice is running:
    curl http://localhost:8000/health
  2. If not running, start it:
    cd microservices/price-stream-service
    python main.py
  3. Check if port 8000 is already in use:
    lsof -ti:8000

Python Dependencies Error

Error: ModuleNotFoundError: No module named 'fastapi'

Solution: Install Python dependencies:

cd microservices/price-stream-service
pip install -r requirements.txt

Or use a virtual environment:

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

WebSocket Connection Refused

Error: WebSocket connection refused on port 8000

Solution:

  1. Ensure microservice is running
  2. Check firewall settings
  3. Verify the microservice is listening on the correct port:
    netstat -an | grep 8000

Development

Adding New Features

  1. Frontend Components: Add to client/src/components/
  2. API Routes: Add to server/routes.ts
  3. Database Models: Update shared/schema.ts and run npm run db:push
  4. Utilities: Add to client/src/lib/ or server/lib/

Database Migrations

After changing the schema in shared/schema.ts:

npm run db:push

Code Style

  • TypeScript strict mode enabled
  • ESLint configuration (if configured)
  • Prettier formatting (if configured)

Environment Variables Reference

Main Application (.env)

Variable Required Default Description
DATABASE_URL ✅ Yes - PostgreSQL connection string (format: postgresql://user:pass@host:5432/db)
JWT_SECRET ✅ Yes - Secret key for JWT tokens (minimum 32 characters, generate with node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
NODE_ENV ❌ No development Environment mode (development or production)
PORT ❌ No 5000 Server port (recommended: 3000 on macOS to avoid AirPlay conflict)

Price Stream Service

The Price Stream Service doesn't require environment variables. It uses TradingView's public API and runs on port 8000 by default.

Configuration options (in main.py if needed):

  • Port: Default 8000
  • Host: Default 0.0.0.0 (all interfaces)
  • Symbols: Defined in STOCK_SYMBOLS and CRYPTO_SYMBOLS constants

Example .env File (Main Application)

# Database (Required)
DATABASE_URL=postgresql://postgres:your_password@localhost:5432/tradePlatform

# JWT Secret (Required - generate a secure random string)
JWT_SECRET=24c91a50ce57d8d77ea70ab081c7eaf4d480bf5930fec2e5dbc5a75ce45d5924

# Server Configuration
NODE_ENV=development
PORT=3000

Note: No additional API keys are required. The Price Stream Service microservice handles all market data.


Security Notes

  • Passwords are hashed with bcrypt (10 rounds)
  • JWT tokens stored in httpOnly cookies (XSS protection)
  • 7-day token expiry
  • Optional TOTP 2FA for enhanced security
  • SQL injection protection via Drizzle ORM
  • Input validation with Zod schemas

Support

For issues and questions:

  • Check the troubleshooting section above
  • Review PROJECT_CONTEXT.md for detailed architecture documentation
  • Check existing issues in the repository

Acknowledgments

  • TradingView for real-time market data API
  • Radix UI for accessible component primitives
  • Tailwind CSS for utility-first styling
  • Drizzle ORM for type-safe database operations
  • FastAPI for high-performance Python microservices

About

All in one platform to trade stocks and cryptocurrency, manage portfolio and get AI suggested recommendations

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 78.8%
  • Python 15.2%
  • HTML 3.3%
  • CSS 2.4%
  • Other 0.3%