A comprehensive full-stack Next.js application that simulates stock trading with virtual currency. Users can buy/sell stocks, track their portfolio, and compete on leaderboards.
- User Management: Registration, login, and authentication with NextAuth
- Virtual Wallet: Starting balance of ₹1,00,000 for each user
- Stock Market Data: Real-time or simulated stock price feeds
- Trading System: Buy/sell stocks with order management
- Portfolio Management: Track holdings, profit/loss, and portfolio value
- Analytics Dashboard: Leaderboard and market overview
- Concurrency Control: Row-level locking to prevent double spending
- Real-time Updates: Stock prices update automatically
- Transaction History: Complete audit trail of all trades
- Portfolio Analytics: Dynamic profit/loss calculations
- Market Screener: Top gainers, losers, and most active stocks
- Frontend: Next.js 14, React, TypeScript, Tailwind CSS
- Backend: Next.js API Routes, Prisma ORM
- Database: PostgreSQL
- Authentication: NextAuth.js
- UI Components: Radix UI, Lucide React
- Charts: Recharts
users- User accounts with wallet balancestocks- Stock information (symbol, name, sector)stock_prices- Historical price data (OHLCV)orders- Trading orders (buy/sell)portfolio- User holdings and P&Ltransactions- Executed trades audit trail
- Node.js 18+
- PostgreSQL database
- npm or yarn
-
Clone and install dependencies
cd virtual-stock-market npm install -
Set up environment variables Create
.env.localfile:DATABASE_URL="postgresql://username:password@localhost:5432/virtual_stock_market?schema=public" NEXTAUTH_URL="http://localhost:3000" NEXTAUTH_SECRET="your-secret-key-here"
-
Set up the database
# Generate Prisma client npx prisma generate # Run database migrations npx prisma migrate dev # Initialize with sample data npm run dev # Then visit: http://localhost:3000/api/init-db
-
Start the development server
npm run dev
-
Access the application
- Open http://localhost:3000
- Register a new account or sign in
- Start trading!
POST /api/auth/register- User registrationPOST /api/auth/[...nextauth]- NextAuth endpoints
GET /api/stocks- Get all stocksGET /api/stocks/[symbol]- Get specific stockPOST /api/stocks/update-prices- Update stock prices
POST /api/trade- Execute tradeGET /api/orders- Get user ordersGET /api/transactions- Get transaction history
GET /api/portfolio- Get user portfolioGET /api/wallet- Get wallet balance
GET /api/leaderboard- Get leaderboardPOST /api/init-db- Initialize database
The trading system uses database transactions with row-level locking to ensure:
- No double spending
- Consistent portfolio updates
- Atomic trade execution
- Random price movements based on volatility
- Realistic market behavior
- Historical price tracking
- Automatic P&L calculations
- Average cost tracking
- Real-time portfolio valuation
- Password hashing with bcrypt
- Session-based authentication
- Input validation and sanitization
# View database in Prisma Studio
npx prisma studio
# Reset database
npx prisma migrate reset
# Deploy migrations
npx prisma migrate deploy- Update Prisma schema if needed
- Run migrations:
npx prisma migrate dev - Update API routes
- Add UI components
- Test thoroughly
-
Environment Setup
- Set production database URL
- Configure NextAuth secrets
- Set up proper CORS
-
Database
- Use managed PostgreSQL (AWS RDS, Supabase, etc.)
- Run migrations:
npx prisma migrate deploy
-
Deployment
- Deploy to Vercel, Netlify, or your preferred platform
- Configure environment variables
- Set up monitoring and logging
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
MIT License - see LICENSE file for details
For issues and questions:
- Check the documentation
- Search existing issues
- Create a new issue with detailed description
Happy Trading! 📈