A professional-grade web-based trading application that provides real-time stock and cryptocurrency market data, portfolio management, account analytics, and secure user authentication.
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:3000That's it! You should see the TradeHub login/register page. Create an account to start trading with $10,000 virtual balance.
- 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
- 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
- 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
-
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-tokenwhen 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; returnsapplication/pdf - REST endpoint:
POST /api/reports/pnl/daily.pdf - Optional email scheduler (daily send) using SMTP envs
- Default port:
8002
-
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(no1W) -
Implementation:
client/src/components/price-chart.tsx:13-19, widget config atclient/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_TOKENenv) - 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
- TradingView API - Real-time market data via Price Stream Service
Before setting up the project, ensure you have the following installed:
- 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
The Price Stream Service microservice is required for real-time market data. Without it running, price data will not be available.
git clone <repository-url>
cd CMPE-272-Projectnpm installThis will install all required dependencies (~530 packages).
Open your terminal and connect to PostgreSQL:
psql -U postgresCreate a new database for the project:
CREATE DATABASE "tradePlatform";Verify the database was created:
\lExit psql:
\qAlternative: One-line command
psql -U postgres -c 'CREATE DATABASE "tradePlatform";'Create a .env file in the project root directory:
touch .envAdd 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=3000DATABASE_URL:
- Replace
postgreswith your PostgreSQL username - Replace
your_passwordwith your PostgreSQL password - Replace
tradePlatformwith 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
5000may conflict with macOS AirPlay Receiver
Run the database migration to create all required tables:
npm run db:pushThis will create the following tables:
users- User authentication and profilesportfolios- User portfolio balancesholdings- Stock and crypto positionstrades- Transaction historypnl_snapshots- Time-series profit/loss data
Expected output:
✓ Pulling schema from database...
✓ Changes applied
The TradeHub platform consists of three core components and two optional microservices:
- Price Stream Service (Python microservice) - Port 8000
- Backend Server (Express.js) - Port 3000
- Frontend (Vite/React) - Served by backend on port 3000
- News Feed Service (Python microservice) - Port 8001 (optional)
- PnL Report Service (Python microservice) - Port 8002 (optional)
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.pyYou 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 devYou 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:
- Frontend & API: http://localhost:3000
- Backend WebSocket: ws://localhost:3000/ws/prices
- Microservice WebSocket: ws://localhost:8000/ws
- Microservice Health: http://localhost:8000/health
If the microservice is not running, you'll see connection errors in the console, and the trading functionality will be limited.
Run the Price Stream Service using Docker:
cd microservices/price-stream-service
docker-compose upNews 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.pyPnL 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.pyNotes:
- 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 theSet-Cookietoken. - Scheduler runs daily at
PNL_REPORT_SEND_TIMEwhen SMTP and recipient are configured.
Check Price Stream Service:
curl http://localhost:8000/healthExpected response:
{
"status": "healthy",
"active_connections": 1,
"active_streams": 20
}Check Main Application:
curl http://localhost:3000/api/stocks/search?q=AAPLExpected: JSON response with stock data
Check Frontend: Open browser to http://localhost:3000 - You should see the login/register page
Build the project for production:
npm run buildThis will:
- Build the frontend (Vite) →
dist/public/ - Bundle the backend (esbuild) →
dist/index.js
Start the production server:
npm startRun TypeScript type checking without building:
npm run check- Navigate to http://localhost:3000
- Click "Register" or go to
/register - Fill in your details:
- Name
- Password (minimum 6 characters)
- Optional: Enable 2FA (scan QR code with authenticator app)
- Click "Register"
- You'll be logged in with $10,000 starting balance
Buy Assets:
- Go to the Dashboard
- Click the "Buy/Sell" tab
- Search for a stock (e.g., "AAPL", "TSLA") or crypto (e.g., "BTC", "ETH")
- Select the asset from results
- Enter the quantity you want to buy
- Click "Buy [Symbol]"
- Your balance will update, and the position will appear in your portfolio
Sell Assets:
- Follow the same steps as buying
- Toggle to "Sell" mode
- Enter quantity to sell
- Click "Sell [Symbol]"
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
Access the admin panel at /admin:
- View all registered users
- Suspend/unsuspend user accounts
- Reset user 2FA
- Delete user accounts
- 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
- BTC - Bitcoin
- ETH - Ethereum
- BNB - Binance Coin
- SOL - Solana
- XRP - Ripple
- ADA - Cardano
- DOGE - Dogecoin
- AVAX - Avalanche
- DOT - Polkadot
- MATIC - Polygon
The Price Stream Service is a standalone Python/FastAPI microservice that provides real-time price streaming for stocks and cryptocurrencies.
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
Main Platform → WebSocket → Price Stream Service → TradingView API
↓ ↓
Backend (Port 3000) FastAPI (Port 8000)
↓
Frontend (React)
Stocks (10): AAPL, TSLA, GOOGL, MSFT, AMZN, META, NVDA, AMD, NFLX, DIS Crypto (10): BTC, ETH, BNB, SOL, XRP, ADA, DOGE, AVAX, DOT, MATIC
ws://localhost:8000/ws- WebSocket endpoint for price streamingGET /health- Health check with active streams infoGET /streams- Detailed stream informationGET /- Service documentation
1. Navigate to microservice directory:
cd microservices/price-stream-service2. Install Python dependencies:
pip install -r requirements.txtOr using a virtual environment (recommended):
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt3. Start the service:
python main.py4. Verify it's running:
curl http://localhost:8000/healthSubscribe 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"
}Using Docker Compose:
cd microservices/price-stream-service
docker-compose upBuilding manually:
docker build -t price-stream-service .
docker run -p 8000:8000 price-stream-service- Memory Usage: 50-100MB
- CPU Usage: <5%
- Latency: <1 second
- Updates: 300+ per minute across all symbols
- Concurrent Streams: 20+ symbols efficiently
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
POST /api/auth/register- Create new userPOST /api/auth/login- Login with credentialsPOST /api/auth/logout- Clear sessionGET /api/auth/me- Get current userPOST /api/auth/2fa/*- 2FA management
GET /api/portfolio- Get portfolio with holdings and tradesGET /api/portfolio/pnl/:period- Get P&L snapshots (24h/30d)
POST /api/trades- Execute buy/sell trade
GET /api/stocks/search?q=<query>- Search assetsGET /api/stocks/:symbol- Get quote for symbolGET /api/stocks/movers- Get market movers
GET /api/admin/users- Get all usersPOST /api/admin/users/:id/suspend- Suspend userPOST /api/admin/users/:id/reset-2fa- Reset 2FADELETE /api/admin/users/:id- Delete user
PUT /api/user/profile- Update profilePOST /api/user/change-password- Change password
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=3000Error: database "tradePlatform" does not exist
Solution: Create the database using psql:
psql -U postgres -c 'CREATE DATABASE "tradePlatform";'Error: DATABASE_URL must be set
Solution:
- Ensure
.envfile exists in the project root - Verify
dotenvis installed:npm install dotenv - Check that
import 'dotenv/config';is at the top ofserver/index.ts
Error: connection to server on socket failed
Solution:
- Verify PostgreSQL is running:
brew services list # macOS sudo systemctl status postgresql # Linux
- Start PostgreSQL if needed:
brew services start postgresql # macOS sudo systemctl start postgresql # Linux
- Verify credentials in
.envare correct
Error: Price not available or Failed to get quote
Solution:
- Ensure the Price Stream Service microservice is running
- Check microservice health:
curl http://localhost:8000/health - Verify the backend is connected to the microservice (check logs for "✅ Connected to price-stream-service")
- Restart both services if needed
Error: TypeScript compilation errors
Solution: Run type checking to see specific errors:
npm run checkError: Failed to connect to price-stream-service
Solution:
- Verify the microservice is running:
curl http://localhost:8000/health
- If not running, start it:
cd microservices/price-stream-service python main.py - Check if port 8000 is already in use:
lsof -ti:8000
Error: ModuleNotFoundError: No module named 'fastapi'
Solution: Install Python dependencies:
cd microservices/price-stream-service
pip install -r requirements.txtOr use a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txtError: WebSocket connection refused on port 8000
Solution:
- Ensure microservice is running
- Check firewall settings
- Verify the microservice is listening on the correct port:
netstat -an | grep 8000
- Frontend Components: Add to
client/src/components/ - API Routes: Add to
server/routes.ts - Database Models: Update
shared/schema.tsand runnpm run db:push - Utilities: Add to
client/src/lib/orserver/lib/
After changing the schema in shared/schema.ts:
npm run db:push- TypeScript strict mode enabled
- ESLint configuration (if configured)
- Prettier formatting (if configured)
| 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) |
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_SYMBOLSandCRYPTO_SYMBOLSconstants
# 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=3000Note: No additional API keys are required. The Price Stream Service microservice handles all market data.
- 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
For issues and questions:
- Check the troubleshooting section above
- Review
PROJECT_CONTEXT.mdfor detailed architecture documentation - Check existing issues in the repository
- 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