Skip to content

KrunalValvi/AlphaMetrics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

7 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

AlphaMetrics โ€” Full Stack NSE Paper Trading Simulator

A professional-grade paper trading simulator for Indian stock markets (NSE), built with React + Vite frontend and Node.js + Express + MongoDB Atlas backend. Real stock prices fetched live from Yahoo Finance.

React Vite Node.js Express MongoDB JWT


๐Ÿ—‚ What's Inside

User Features

Feature Description
๐Ÿ“Š Dashboard Live portfolio value, real P&L, equity curve from actual trades, top gainers/losers
๐Ÿ“ˆ Market Live/simulated NSE stock prices, interactive price charts (1W/1M/3M/1Y)
๐Ÿ” Stock Detail Full stock stats, candlestick chart, news, set price alerts โ€” all in one page
๐Ÿ’ผ Portfolio Open positions with live P&L, real equity curve, sector allocation
๐Ÿ“‹ Orders Complete trade history with filters
โญ Watchlist Add/remove stocks, live price updates
๐Ÿ† Leaderboard Real-time ranking of all traders by P&L
๐Ÿ”” Price Alerts Set target prices โ€” server checks every 60s and triggers alerts
โŸณ Backtesting Test 6 strategies (SMA, EMA, RSI, MACD, Bollinger, S&R) on any stock
โš™ Settings Edit profile, avatar color, set/top-up balance, reset portfolio, data mode toggle

Admin Features

Feature Description
Admin Dashboard Platform-wide stats, real trade volume chart, recent users & trades
User Management View all users, activate/deactivate accounts
All Trades Full platform trade history with search and filters
Analytics Leaderboard, sector distribution, retention chart
Admin Settings Admin-level platform configuration

Smart Data Mode Toggle

Switch between two modes anytime from the sidebar or Settings:

  • ๐ŸŽฎ Simulation โ€” Simulated prices that update every 3 seconds. Works 24/7, perfect for after-hours testing
  • ๐ŸŒ Live โ€” Real NSE prices from Yahoo Finance. Works during market hours (9:15 AM โ€“ 3:30 PM IST, weekdays)

Project Structure

alphametrics/
โ”œโ”€โ”€ package.json                โ† root โ€” runs both frontend + backend together
โ”œโ”€โ”€ vercel.json                 โ† Vercel deploy config (auto SPA rewrite)
โ”œโ”€โ”€ backend/
โ”‚   โ”œโ”€โ”€ package.json
โ”‚   โ”œโ”€โ”€ .env                    โ† MongoDB Atlas URI + JWT secret (edit this)
โ”‚   โ””โ”€โ”€ src/
โ”‚       โ”œโ”€โ”€ index.js            โ† Express server + price alert cron job
โ”‚       โ”œโ”€โ”€ seed.js             โ† Creates demo users in MongoDB
โ”‚       โ”œโ”€โ”€ models/             โ† User, Trade, Position, Alert, PnlSnapshot
โ”‚       โ”œโ”€โ”€ routes/             โ† auth, stocks, trades, portfolio, watchlist,
โ”‚       โ”‚                          alerts, leaderboard, backtest, admin
โ”‚       โ””โ”€โ”€ middleware/         โ† JWT auth guard
โ””โ”€โ”€ frontend/
    โ”œโ”€โ”€ package.json
    โ”œโ”€โ”€ vite.config.js          โ† Vite 5 + proxy to backend :5000
    โ”œโ”€โ”€ index.html
    โ””โ”€โ”€ src/
        โ”œโ”€โ”€ main.jsx
        โ”œโ”€โ”€ App.jsx             โ† All routes defined here
        โ”œโ”€โ”€ index.css           โ† Global design system & tokens
        โ”œโ”€โ”€ api/index.js        โ† All API calls in one place
        โ”œโ”€โ”€ context/
        โ”‚   โ””โ”€โ”€ AuthContext.jsx โ† Auth, balance, watchlist, data mode state
        โ”œโ”€โ”€ data/
        โ”‚   โ”œโ”€โ”€ mockStocks.js   โ† Simulation mode price generator
        โ”‚   โ””โ”€โ”€ mockData.jsx    โ† Chart helpers + backtest utilities
        โ”œโ”€โ”€ components/         โ† AppLayout, Sidebar, Topbar, BuySellModal
        โ””โ”€โ”€ pages/
            โ”œโ”€โ”€ AuthPage.jsx
            โ”œโ”€โ”€ LandingPage.jsx
            โ”œโ”€โ”€ user/           โ† Dashboard, Market, StockDetail, Portfolio,
            โ”‚                      Orders, Watchlist, Backtest, Leaderboard,
            โ”‚                      Alerts, UserSettings
            โ””โ”€โ”€ admin/          โ† AdminDashboard, AdminUsers, AdminTrades,
                                   AdminAnalytics, AdminSettings

Prerequisites

  • Node.js v18 or higher โ€” check with node -v
  • MongoDB Atlas free account โ€” no local database needed

Step 1 โ€” Create MongoDB Atlas Cluster (free)

  1. Go to cloud.mongodb.com โ†’ sign in or register
  2. Click "Build a Database" โ†’ choose Free (M0) โ†’ any region โ†’ Create
  3. Set a Username and Password (save these!)
  4. Go to Network Access โ†’ Add IP Address โ†’ "Allow Access from Anywhere" (0.0.0.0/0) โ†’ Confirm
  5. Go to Database โ†’ Connect โ†’ Drivers โ†’ copy the connection string:
    mongodb+srv://youruser:[email protected]/?retryWrites=true&w=majority
    

Step 2 โ€” Configure Environment

Open backend/.env and paste your connection string:

PORT=5000
MONGO_URI=mongodb+srv://youruser:[email protected]/alphametrics?retryWrites=true&w=majority
JWT_SECRET=alphametrics_super_secret_key_change_in_production

Replace youruser, yourpassword, and cluster0.xxxxx with your real values. The /alphametrics at the end is the database name โ€” Atlas creates it automatically.


Step 3 โ€” Install All Dependencies

# Run from the root alphametrics/ folder
npm install
npm install --prefix backend
npm install --prefix frontend

Or use the shorthand script:

npm run install:all

Step 4 โ€” Seed Demo Users (run once)

cd backend
node src/seed.js
cd ..

Expected output:

โœ… Connected to MongoDB
๐Ÿ—‘  Cleared existing users
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
   โœ“ Created: [email protected]
๐ŸŒฑ Seed complete! Demo accounts ready.

Step 5 โ€” Run the Project

# From the root alphametrics/ folder
npm run dev

This starts both servers simultaneously:

Open http://localhost:5173 in your browser.


Demo Accounts

Role Email Password
๐Ÿ‘ค User [email protected] password123
๐Ÿ‘ค User [email protected] password123
๐Ÿ‘ค User [email protected] password123
๐Ÿ”‘ Admin [email protected] admin123

All user accounts use password123. Admin uses admin123.


API Reference

Auth

Method Endpoint Auth Description
POST /api/auth/signup Public Register new user
POST /api/auth/login Public Login, returns JWT token
GET /api/auth/me User Get current logged-in user
PATCH /api/auth/profile User Update name, email, password, balance, avatar
POST /api/auth/reset-portfolio User Wipe trades & positions, restore balance

Stocks

Method Endpoint Auth Description
GET /api/stocks User All NSE quotes (60s cache)
GET /api/stocks/:symbol User Single stock quote
GET /api/stocks/:symbol/history?period=3M User Historical OHLC candles

Trading

Method Endpoint Auth Description
GET /api/trades User User's full order history
POST /api/trades User Execute BUY or SELL order
GET /api/portfolio User Open positions
GET /api/portfolio/equity?days=30 User Real equity curve from trade history
GET /api/portfolio/stats User Day P&L, trade counts

Watchlist & Alerts

Method Endpoint Auth Description
GET /api/watchlist User Get watchlist symbols
POST /api/watchlist/:symbol User Add symbol
DELETE /api/watchlist/:symbol User Remove symbol
GET /api/alerts User Get all alerts
POST /api/alerts User Create price alert
DELETE /api/alerts/:id User Delete alert
PATCH /api/alerts/:id/reset User Re-arm triggered alert

Backtesting

Method Endpoint Auth Description
POST /api/backtest User Run strategy backtest โ€” returns totalReturn, winRate, maxDrawdown, sharpeRatio

Leaderboard & Admin

Method Endpoint Auth Description
GET /api/leaderboard User Top 20 traders ranked by P&L
GET /api/admin/stats Admin Platform KPIs
GET /api/admin/users Admin All users
PATCH /api/admin/users/:id/status Admin Activate / deactivate user
GET /api/admin/trades Admin All platform trades

Tech Stack

Layer Technology
Frontend React 18.3, Vite 5.3, React Router 6.23
Charts Recharts 2.12
Backend Node.js 18+, Express 4.19
Database MongoDB Atlas + Mongoose 8.4
Auth JWT (jsonwebtoken 9.0) + bcryptjs 2.4
Rate Limiting express-rate-limit 7.1
Stock Data yahoo-finance2 2.11 (real NSE prices via .NS suffix)
Monorepo concurrently 8.2 (single npm run dev command)

How It Works

Stock prices โ€” Yahoo Finance is queried using NSE symbols with the .NS suffix (e.g. RELIANCE.NS). Results are cached in memory for 60 seconds to avoid rate limiting.

Trading โ€” When a user executes a BUY, the trade is saved to MongoDB, the position is created/updated with weighted average price, and the user's balance is deducted. SELL does the reverse and calculates realized P&L.

Equity curve โ€” The portfolio chart is built by replaying all of the user's actual trades day-by-day from MongoDB โ€” not random data.

Backtesting โ€” The /api/backtest endpoint fetches historical OHLC data from Yahoo Finance, runs the selected strategy to generate buy/sell signals, simulates trades, and returns metrics: total return, win rate, max drawdown, and annualized Sharpe ratio.

Price alerts โ€” A setInterval on the backend checks all active alerts every 60 seconds against live Yahoo Finance prices and marks them as triggered when the target is hit.

JWT auth โ€” Tokens are stored in localStorage under am_token and sent as Bearer headers on every API request.


Common Commands

# Install everything
npm run install:all

# Seed demo users (run from root)
cd backend && node src/seed.js && cd ..

# Start everything
npm run dev

# Start only backend
npm run backend

# Start only frontend
npm run frontend

Troubleshooting

MongoDB connection fails โ€” Check your Atlas URI in backend/.env. Make sure Network Access has 0.0.0.0/0 and your username/password are correct.

"Cannot find module seed.js" โ€” You must cd backend first before running node src/seed.js.

Market shows no data โ€” Switch to Simulation mode in the sidebar toggle (market may be closed). Live data only works 9:15 AM โ€“ 3:30 PM IST on weekdays.

Vite JSX error โ€” Make sure all files containing JSX use the .jsx extension, not .js.

Rate limit errors โ€” The backend uses express-rate-limit. If you're hitting limits during development, reduce your polling interval or restart the backend server.


Deploying to Production

Architecture

  • Frontend โ†’ Vercel (auto-deploy from GitHub, vercel.json included)
  • Backend โ†’ Render.com free tier (always-on Node server)
  • Database โ†’ MongoDB Atlas (already configured)

Step 1 โ€” Deploy Backend on Render

  1. Go to render.com โ†’ New โ†’ Web Service
  2. Connect your GitHub repo
  3. Set these fields:
    • Root Directory: backend
    • Build Command: npm install
    • Start Command: node src/index.js
    • Environment: Node
  4. Add Environment Variables (do NOT put these in .env on GitHub):
    MONGO_URI       = your MongoDB Atlas URI
    JWT_SECRET      = a strong random secret (openssl rand -hex 32)
    FRONTEND_URL    = https://your-app.vercel.app   โ† add after Vercel deploy
    PORT            = 10000
    
  5. Deploy โ€” copy the Render URL e.g. https://alphametrics-api.onrender.com

Step 2 โ€” Deploy Frontend on Vercel

  1. Go to vercel.com โ†’ New Project โ†’ Import GitHub repo
  2. Vercel auto-detects settings from vercel.json โ€” no changes needed
  3. Add Environment Variable in Vercel dashboard:
    VITE_API_URL = https://alphametrics-api.onrender.com
    
  4. Deploy

Step 3 โ€” Connect them

  1. Copy your Vercel URL e.g. https://alphametrics.vercel.app
  2. Go back to Render โ†’ your backend service โ†’ Environment tab
  3. Set FRONTEND_URL = https://alphametrics.vercel.app
  4. Click Save โ€” Render redeploys automatically

Step 4 โ€” Update frontend API base URL

In frontend/src/api/index.js, change:

const BASE = "/api";

to:

const BASE = import.meta.env.VITE_API_URL
  ? `${import.meta.env.VITE_API_URL}/api`
  : "/api";

This makes it use localhost:5000 locally and your Render URL in production.


Security checklist before going live

  • backend/.env is in .gitignore โœ…
  • All secrets set as environment variables on Render, NOT in code
  • JWT_SECRET changed from the default placeholder
  • MongoDB Atlas Network Access includes 0.0.0.0/0 (for Render's dynamic IPs)

About

๐Ÿ‡ฎ๐Ÿ‡ณ Indian paper trading app built with React. Practice NSE/BSE trading risk-free with โ‚น10L virtual cash, strategy backtesting, and portfolio analytics.

Topics

Resources

Stars

Watchers

Forks

Contributors