This is a public fork of my project at LUMS - An AI Trading Simulation game Deployment:https://p04-trade-up.vercel.app/
- New Module:
src/trades/trades.controller.ts- Buy/Sell endpointstrades.service.ts- Trading business logicdto/buy-stock.dto.ts- Buy validationdto/sell-stock.dto.ts- Sell validationtrades.module.ts- Module definition
-
New Model:
Portfolio- Tracks user stock holdings
- Fields: id, userId, stockId, quantity, avgPrice, createdAt
- Unique constraint: userId + stockId
-
New Model:
Transaction- Records all buy/sell operations
- Fields: id, userId, stockId, type, quantity, price, total, createdAt
- Enums: TransactionType (BUY, SELL)
-
User Model Updates
- Added
balancefield (Decimal, default: 1000000 PKR) - Added
namefield (String, optional) - Added
profileImageUrlfield (String, optional) - Added relations: portfolio[], transactions[]
- Added
-
Stock Model Updates
- Added relations: portfolio[], transactions[]
- Auth: Required (JWT)
- Body:
{ "symbol": "HBL", "quantity": 10 } - Response: User balance, portfolio item, transaction
- Validation: symbol (required), quantity (≥ 1)
- Errors: Insufficient balance, stock not found
- Auth: Required (JWT)
- Body:
{ "symbol": "HBL", "quantity": 5 } - Response: User balance, portfolio item, transaction
- Validation: symbol (required), quantity (≥ 1)
- Errors: Insufficient shares, stock not found
- Auth: Required (JWT)
- Response:
- balance, totalInvested, totalPortfolioValue
- totalUnrealizedPnl, totalPnlPercentage
- totalAccountValue
- portfolio array with P&L calculations
- Auth: Required (JWT)
- Query: ?limit=50&offset=0
- Response: Paginated transaction history with metadata
-
app/buy/page.tsx- Buy stocks interface- Stock selection dropdown
- Quantity input with validation
- Current price display
- Total cost calculation
- Balance check
-
app/portfolio/page.tsx- Portfolio & transactions- Portfolio overview with total value
- Holdings table with P&L
- Transaction history with pagination
- Sell functionality
- New Module:
src/news/news.controller.ts- News endpointsnews.module.ts- Module definition
- Auth: Not required
- Response: Array of latest market news articles
- API: Financial Modeling Prep
- Auth: Not required
- Body:
{ "ticker": "HBL" } - Response: Stock-specific news articles
- API: MarketAux
-
lib/newsService.ts- News API servicefetchLatestNews()- Get latest newsfetchStockNews(ticker)- Get stock-specific news
-
types/news.ts- TypeScript typesNewsArticleinterfaceStockNewsArticleinterface- Response type definitions
-
app/news/page.tsx- News feed page- Latest market news display
- News articles with images
- Stock-specific filtering
- Auth: Required (JWT)
- Response: User profile (id, email, name, role, balance, profileImageUrl)
- Auth: Required (JWT)
- Body:
{ "newEmail": "...", "currentPassword": "..." } - Response: Updated user profile
- Auth: Required (JWT)
- Body:
{ "currentPassword": "...", "newPassword": "..." } - Response: Success message
- Auth: Required (JWT)
- Body:
{ "newName": "...", "currentPassword": "..." } - Response: Updated user profile
- Auth: Required (JWT)
- Body:
file(multipart/form-data) - Response:
{ "imageUrl": "..." }
-
lib/userService.ts- User management serviceuploadProfileImage(file)- Upload profile picturegetUserProfile()- Get user profileupdateUserEmail(newEmail, currentPassword)updateUserPassword(currentPassword, newPassword)updateUserName(newName, currentPassword)
-
app/settings/page.tsx- Settings page- Update name, email, password
- Upload profile picture
- View account information
app/help/page.tsx- Help & documentationapp/settings/page.tsx- User profile settingsapp/news/page.tsx- Latest news feedapp/portfolio/page.tsx- Portfolio managementapp/buy/page.tsx- Buy stocks interface
components/auth/auth-form.tsx- Login/Signup formcomponents/auth/role-chip.tsx- Role display chipcomponents/auth/tagline.tsx- Tagline componentcomponents/spinner.tsx- Loading spinnercomponents/topbar.tsx- Navigation top bar
context/UserContext.tsx- User authentication context- Provides user state and authentication methods
- Replaces localStorage-based auth with React context
lib/api.ts- API base URL configuration- Production:
https://p04-trade-up1.vercel.app - Development:
http://localhost:3001
- Production:
model User {
id Int @id @default(autoincrement())
email String @unique
passwordHash String
role Role @default(TRADER)
createdAt DateTime @default(now())
balance Decimal @default(1000000) // NEW
name String? // NEW
profileImageUrl String? // NEW
portfolio Portfolio[]
transactions Transaction[]
watchlist WatchlistItem[]
}
model Stock {
id Int @id @default(autoincrement())
symbol String @unique
name String?
marketType String @default("REG")
createdAt DateTime @default(now())
portfolio Portfolio[] // NEW
transactions Transaction[] // NEW
watchers WatchlistItem[]
}
model WatchlistItem {
id Int @id @default(autoincrement())
userId Int
stockId Int
createdAt DateTime @default(now())
stock Stock @relation(fields: [stockId], references: [id])
user User @relation(fields: [userId], references: [id])
@@unique([userId, stockId])
}
model Portfolio {
id Int @id @default(autoincrement())
userId Int
stockId Int
quantity Int
avgPrice Decimal
createdAt DateTime @default(now())
stock Stock @relation(fields: [stockId], references: [id])
user User @relation(fields: [userId], references: [id])
@@unique([userId, stockId])
}
model Transaction {
id Int @id @default(autoincrement())
userId Int
stockId Int
type TransactionType
quantity Int
price Decimal
total Decimal
createdAt DateTime @default(now())
stock Stock @relation(fields: [stockId], references: [id])
user User @relation(fields: [userId], references: [id])
}
enum Role {
TRADER
ADMIN
}
enum TransactionType {
BUY
SELL
}
- NestJS: 11.0.1 (updated from 10.x)
- Next.js: 16.0.7 (updated from 16.0.0)
- React: 19.2.0
@nestjs/axios: ^4.0.1 - HTTP client for news API@prisma/client: ^6.18.0 - Prisma ORM
@radix-ui/react-avatar: ^1.1.11 - Avatar component@radix-ui/react-label: ^2.1.7 - Label component@radix-ui/react-separator: ^1.1.7 - Separator component@radix-ui/react-slot: ^1.2.3 - Slot componentclass-variance-authority: ^0.7.1 - Variant utilitiesclsx: ^2.1.1 - Class name utilitieslightweight-charts: ^4.1.3 - Candlestick chartslucide-react: ^0.552.0 - Icon librarynext: ^16.0.7 - Next.js frameworkreact: 19.2.0 - React libraryreact-dom: 19.2.0 - React DOMreact-hook-form: ^7.66.0 - Form managementtailwind-merge: ^3.3.1 - Tailwind class mergingzod: ^4.1.12 - Validation
| Category | Endpoint | Method | Auth Required | Description |
|---|---|---|---|---|
| Trades | /trades/buy |
POST | ✓ | Buy stocks |
| Trades | /trades/sell |
POST | ✓ | Sell stocks |
| Trades | /trades/portfolio |
GET | ✓ | Get portfolio with P&L |
| Trades | /trades/transactions |
GET | ✓ | Get transaction history |
| News | /news/latest |
GET | ✗ | Get latest market news |
| News | /news/stock |
POST | ✗ | Get stock-specific news |
| Users | /users/profile |
GET | ✓ | Get user profile |
| Users | /users/email |
PUT | ✓ | Update email |
| Users | /users/password |
PUT | ✓ | Update password |
| Users | /users/name |
PUT | ✓ | Update name |
| Users | /users/profile-picture |
POST | ✓ | Upload profile picture |
frontend/
├── app/
│ ├── buy/ # NEW - Buy page
│ ├── portfolio/ # NEW - Portfolio page
│ ├── settings/ # NEW - Settings page
│ ├── help/ # NEW - Help page
│ ├── news/ # NEW - News page
│ ├── dashboard/
│ ├── charts/
│ ├── layout.tsx
│ └── page.tsx
│
├── components/
│ ├── auth/ # NEW - Auth components
│ │ ├── auth-form.tsx
│ │ ├── role-chip.tsx
│ │ └── tagline.tsx
│ ├── spinner.tsx # NEW - Loading spinner
│ ├── topbar.tsx # NEW - Navigation bar
│ └── ui/
│ └── ... (existing)
│
├── context/ # NEW - React context
│ └── UserContext.tsx
│
├── lib/
│ ├── api.ts # NEW - API config
│ ├── newsService.ts # NEW - News service
│ ├── userService.ts # UPDATED - User service
│ └── utils.ts
│
└── types/ # NEW - TypeScript types
└── news.ts
- ✓ User authentication
- ✓ Stock market data
- ✓ Watchlist management
- ✓ Real-time updates
- ✓ Live candlestick charts
- ✓ Guest browsing
- ✓ Buy/Sell trading
- ✓ Portfolio management
- ✓ Transaction history
- ✓ News feed
- ✓ User profile settings
- ✓ Profile pictures
- ✓ Additional pages (Help, Settings)
- Advanced charts (multiple timeframes, indicators)
- AI features
- Gamification
- Community features
- Educational content
- Mobile app
- Admin dashboard
-
20251022144710_user_auth_watchlist
- Initial schema: User, Stock, WatchlistItem
-
20251124123310_add_user_name_field
- Added
namefield to User model
- Added
-
20251128183330_add_profile_image_url
- Added
profileImageUrlfield to User model
- Added
-
20251130163218_add_user_balance_field
- Added
balancefield to User model
- Added
-
20251130210857_change_default_balance_to_neg1
- Changed default balance from 1000000 to -1 (temporary)
- Note: Current default is -1, should be updated to 1000000 for production
The balance field default should be updated from -1 to 1000000 for proper functionality.
New Variables:
NEWS_API_KEY=your-news-api-key
STOCK_API_KEY=your-stock-api-key
Updated Variable:
NEXT_PUBLIC_API_BASE_URL=http://localhost:3001
- ✓ Backend builds successfully
- ✓ Frontend builds successfully
- ✓ All TypeScript checks pass
- ✓ All ESLint checks pass
- Backend: Can be deployed to Vercel, Railway, or any Node.js host
- Frontend: Deployed to Vercel (https://p04-trade-up1.vercel.app)
- ✓ User registration and login
- ✓ Stock data fetching
- ✓ Watchlist management
- ✓ Buy/sell transactions
- ✓ Portfolio calculations
- ✓ Transaction history
- ✓ News feed
- ✓ Profile updates
- ✓ Profile picture upload
- Unit tests: Basic structure in place
- E2E tests: Basic structure in place
- Integration tests: Not fully implemented
- Balance Default: User balance defaults to -1 instead of 1000000
- News API Keys: Required for news feed to work
- Stock News: Limited to 3 articles per request
- WebSocket: Only works when backend is running
- PSX API: Rate limited to 100 requests per minute
- Balance: Update migration or manually set balance after user creation
- News API: Use free tiers or obtain API keys
- WebSocket: Ensure backend is always running
- PSX API: Implement caching and rate limiting
- ✓ Prisma transactions for atomic operations
- ✓ WebSocket for real-time updates
- ✓ Pagination for transaction history
- ✓ Caching in browser (localStorage)
- ✓ Efficient database queries
- Redis caching for frequent queries
- Query optimization for portfolio calculations
- Load testing and benchmarking
- Database indexing optimization
- ✓ Password hashing with bcrypt
- ✓ JWT authentication with 7-day expiration
- ✓ Input validation with DTOs
- ✓ SQL injection prevention (Prisma ORM)
- ✓ CORS configuration
- ✓ Rate limiting (throttler module)
- Implement refresh tokens
- Add CSRF protection
- Implement security headers
- Regular security audits
- Dependency vulnerability scanning
- ✓ README.md (this document)
- ✓ CHANGES_SUMMARY.md (new)
- ✓ Backend README (if exists)
- ✓ Frontend README (if exists)
- ✓ API documentation complete
- ✓ Setup instructions complete
- ✓ Troubleshooting guide complete
- ✓ Code standards documented
| Version | Date | Description |
|---|---|---|
| 1.0.0 | 2025-11-06 | Phase 1 Complete - Auth, Watchlist, Real-time Updates, Charts |
| 2.0.0 | 2025-12-16 | Phase 2 Complete - Trading System, Portfolio, News Feed, User Profile |
- Fix balance default value (-1 → 1000000)
- Add proper error handling for news API
- Implement loading states in UI
- Add more comprehensive tests
- Improve documentation
- Advanced charting features
- Technical indicators
- AI-powered insights
- Mobile application
- Gamification elements
- Social features
The TradeUp project has successfully completed Phase 2 with the following major additions:
- Trading System - Full buy/sell functionality with portfolio tracking
- News Feed - Latest market news and stock-specific articles
- User Profile - Profile management with profile pictures
- Additional Pages - Help, Settings, Portfolio, Buy interfaces
- Enhanced Architecture - React Context, improved service layer
Last Updated: December 16, 2025