A full-stack web application for stock market trading, featuring user authentication, order management, and a real-time trading dashboard.
This is a modern stock market trading platform built with:
- Frontend: React with Material-UI and Bootstrap for responsive UI
- Backend: Node.js with Express.js for API management
- Database: MongoDB for data persistence
- Authentication: JWT-based authentication with bcrypt password hashing
STOCK MARKET-2/
βββ backend/ # Express.js server
β βββ index.js # Main server file
β βββ package.json # Backend dependencies
β βββ middleware/
β β βββ authMiddleware.js # JWT authentication middleware
β βββ models/
β β βββ UserModel.js # User schema & model
β β βββ HoldingsModel.js # Stock holdings model
β β βββ OrdersModel.js # Trading orders model
β β βββ PositionsModel.js # Open positions model
β βββ routes/
β β βββ authRoutes.js # Authentication endpoints
β βββ schemas/
β βββ HoldingsSchema.js # Holdings schema definition
β βββ OrdersSchema.js # Orders schema definition
β βββ PositionsSchema.js # Positions schema definition
βββ dashboard/ # React application
βββ package.json # Frontend dependencies
βββ public/
β βββ index.html # Main HTML file
βββ src/
βββ index.js # React entry point
βββ index.css # Global styles
βββ components/ # React components
βββ Home.js
βββ Apps.js
βββ ...
- β User Authentication: Register and login with secure password hashing
- β JWT Tokens: Stateless authentication with 1-hour expiration
- β Protected Routes: Authentication middleware protects API endpoints
- β Order Management: Create new trading orders
- β Portfolio Tracking: Store and retrieve stock holdings
- β Position Management: Track open trading positions
- β MongoDB Integration: Persistent data storage
- π Interactive Dashboard: Real-time trading data visualization
- π Chart Integration: Chart.js for financial data visualization
- π Secure Authentication: Login/Register with JWT tokens
- π± Responsive Design: Bootstrap & Material-UI for mobile-friendly interface
- π¨ Material Design: Professional UI with Material-UI components
- Node.js (v14 or higher)
- npm (v6 or higher)
- MongoDB (local or cloud instance)
-
Clone the repository (if not already done)
cd "STOCK MARKET-2"
-
Create
.envfile in thebackenddirectorycd backend touch .env -
Add the following environment variables to
backend/.envPORT=3002 MONGO_URL=mongodb://localhost:27017/stock-market JWT_SECRET=your_secret_key_here NODE_ENV=developmentExample for MongoDB Cloud (Atlas):
MONGO_URL=mongodb+srv://username:password@cluster.mongodb.net/stock-market?retryWrites=true&w=majority
cd backend
npm install
npm startExpected Output:
β
Connected to MongoDB
π Server running on port 3002
cd dashboard
npm install
npm startThe dashboard will open at http://localhost:3000
Base URL: http://localhost:3002/api/auth
POST /api/auth/register
Content-Type: application/json
{
"username": "john_doe",
"email": "john@example.com",
"password": "securePassword123"
}Response (Success - 201):
{
"message": "User created successfully!",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"username": "john_doe"
}Response (Error - 400):
{
"message": "User already exists..."
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "securePassword123"
}Response (Success - 200):
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}All requests must include the Authorization header:
Authorization: Bearer <your_jwt_token>GET /addHoldings
Authorization: Bearer <token>Response:
[
{
"_id": "507f1f77bcf86cd799439011",
"symbol": "AAPL",
"quantity": 10,
"avgPrice": 150.25,
"currentPrice": 155.00,
...
}
]GET /addPositions
Authorization: Bearer <token>Response:
[
{
"_id": "507f1f77bcf86cd799439012",
"symbol": "GOOGL",
"entryPrice": 2800,
"quantity": 5,
"pnl": 250,
...
}
]POST /newOrder
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "AAPL",
"qty": 5,
"price": 150.25,
"mode": "BUY"
}Response (Success - 201):
{
"message": "Order created successfully"
}{
username: String (required),
email: String (required, unique, lowercase),
password: String (required, hashed with bcryptjs),
createdAt: Date (auto-generated)
}{
userId: ObjectId (reference to User),
symbol: String,
quantity: Number,
avgPrice: Number,
currentPrice: Number,
totalValue: Number,
createdAt: Date,
updatedAt: Date
}{
userId: ObjectId (reference to User),
name: String (stock symbol),
qty: Number,
price: Number,
mode: String (BUY or SELL),
status: String (PENDING, COMPLETED, CANCELLED),
orderDate: Date,
executionDate: Date
}{
userId: ObjectId (reference to User),
symbol: String,
entryPrice: Number,
quantity: Number,
currentPrice: Number,
pnl: Number (Profit/Loss),
openDate: Date,
closeDate: Date
}- User submits username, email, and password
- Backend checks if user already exists
- Password is hashed using bcryptjs (12 salt rounds)
- User is saved to MongoDB
- JWT token is generated (expires in 1 hour)
- Token is returned to frontend
- User submits email and password
- Backend finds user by email
- Password is compared with stored hash using bcrypt
- If match, JWT token is generated
- Token is returned to client
- Frontend sends request with
Authorization: Bearer <token>header - Middleware extracts and verifies token
- If valid, request proceeds to route handler
- If invalid/expired, 401 Unauthorized is returned
| Technology | Version | Purpose |
|---|---|---|
| Express.js | ^5.1.0 | Web framework |
| Mongoose | ^8.19.1 | MongoDB ODM |
| MongoDB | ^6.20.0 | Database |
| jsonwebtoken | ^9.0.2 | JWT authentication |
| bcryptjs | ^3.0.2 | Password hashing |
| Passport.js | ^0.7.0 | Authentication strategies |
| CORS | ^2.8.5 | Cross-origin requests |
| dotenv | ^17.2.3 | Environment variables |
| nodemon | ^3.1.10 | Development auto-reload |
| Technology | Version | Purpose |
|---|---|---|
| React | ^18.2.0 | UI library |
| React Router | ^6.22.2 | Navigation |
| Material-UI (MUI) | ^5.15.11 | Component library |
| Bootstrap | ^5.3.8 | CSS framework |
| Chart.js | ^4.5.1 | Data visualization |
| react-chartjs-2 | ^5.3.0 | React wrapper for Chart.js |
| Axios | ^1.12.2 | HTTP client |
| Emotion | ^11.11.4 | CSS-in-JS styling |
Terminal 1 - Backend:
cd backend
npm start
# Output: π Server running on port 3002Terminal 2 - Frontend:
cd dashboard
npm start
# Opens http://localhost:3000Build Frontend:
cd dashboard
npm run build
# Creates optimized build in dashboard/buildRun Backend:
cd backend
NODE_ENV=production npm start- Register/Login: Create an account or login with existing credentials
- View Dashboard: See your portfolio, holdings, and positions
- Place Orders: Create buy/sell orders for stocks
- Track Performance: Monitor your trading positions and P&L
- View Analytics: Use charts to analyze trading data
1. Register:
curl -X POST http://localhost:3002/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "trader_john",
"email": "john@trading.com",
"password": "Trade@123"
}'Response:
{
"message": "User created successfully!",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjVhOGM0YjQ4YzMwMDAwMDAwMDAwMDAxIn0sImlhdCI6MTcwNTQ0OTQyOCwiZXhwIjoxNzA1NDUzMDI4fQ.abc123...",
"username": "trader_john"
}2. Place Order with Token:
curl -X POST http://localhost:3002/newOrder \
-H "Content-Type: application/json" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-d '{
"name": "MSFT",
"qty": 10,
"price": 380.50,
"mode": "BUY"
}'Response:
{
"message": "Order created successfully"
}Error: β MongoDB connection error: connect ECONNREFUSED
Solution:
- Ensure MongoDB is running:
mongod(local) or check MongoDB Atlas credentials - Verify
MONGO_URLin.envfile - Check network connection if using MongoDB Cloud
Error: 401 Not authorized, token failed
Solution:
- Tokens expire after 1 hour
- Re-login to get a new token
- Store token securely on frontend
Error: Access to XMLHttpRequest blocked by CORS policy
Solution:
- CORS is already enabled in backend
- Verify frontend and backend are running on correct ports
- Check
Authorizationheader is being sent correctly
Error: Address already in use :::3002
Solution:
# Find process using port 3002
lsof -i :3002
# Kill the process
kill -9 <PID># Server Configuration
PORT=3002
NODE_ENV=development
# Database
MONGO_URL=mongodb://localhost:27017/stock-market
# Authentication
JWT_SECRET=your_super_secret_key_change_in_production
# Optional
LOG_LEVEL=debug- β Passwords are hashed with bcryptjs (12 salt rounds)
- β JWT tokens have 1-hour expiration
- β Protected routes require valid tokens
- β Environment variables store sensitive data
β οΈ TODO: Implement HTTPS/TLS for productionβ οΈ TODO: Add rate limiting to prevent brute force attacksβ οΈ TODO: Implement refresh tokens for better UX
- Real-time stock price updates with WebSockets
- Advanced charting with technical indicators
- Portfolio analytics and performance metrics
- Email notifications for order execution
- Two-factor authentication (2FA)
- User profile management
- Watchlist feature
- Trade history and reports
- Mobile app (React Native)
- Paper trading mode for practice
This is a personal project. For improvements or bug reports, please document issues clearly.
ISC License - See package.json for details
For issues or questions:
- Check the Troubleshooting section above
- Verify all environment variables are set correctly
- Check MongoDB connection
- Review server logs in terminal
Last Updated: March 10, 2026