SkillAgentSearch skills...

TradeSphere

TradeSphere — Real-time stock exchange simulator with order matching engine, Redis order book, BullMQ background jobs, Socket.IO live updates, and ML-powered price predictions via a Flask microservice.

Install / Use

/learn @vikram-codes-hub/TradeSphere
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

TradeSphere 📈

AI-Powered Stock Exchange Simulator

<div align="center">

TradeSphere Banner

Node.js React Python MongoDB Redis Socket.IO

A real-time stock exchange simulator with a custom order matching engine, Redis-backed order book, BullMQ background jobs, and an ML prediction microservice — built to simulate how real exchanges like NSE and NASDAQ operate under the hood.

Live Demo · Report Bug · Request Feature

</div>

📌 Table of Contents


🎯 Overview

TradeSphere is a full-stack, three-service microservice system that simulates a real stock exchange. It is not a CRUD application — it implements actual financial system concepts:

  • A custom order matching engine that pairs buy and sell orders when price conditions are met
  • A Redis-backed order book using sorted sets for O(log n) order insertion and retrieval
  • BullMQ background workers so heavy tasks never block the Express API
  • A separate Flask ML microservice that trains on real OHLCV data and predicts next-day stock prices
  • Socket.IO rooms per stock symbol so clients only receive updates for stocks they are watching

🏗️ Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        React Frontend                           │
│              (Vite + Tailwind CSS + Chart.js)                   │
│         HTTP via Axios  │  WebSocket via Socket.IO              │
└─────────────┬───────────┴──────────────┬───────────────────────┘
              │                          │
              ▼                          ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Node.js Backend                             │
│                  (Express + Socket.IO)                          │
│                                                                 │
│   ┌──────────┐  ┌──────────┐  ┌────────────┐  ┌────────────┐  │
│   │ MongoDB  │  │  Redis   │  │   BullMQ   │  │  JWT Auth  │  │
│   │ (Mongoose│  │(Order Bk)│  │  (Queues)  │  │  (3 roles) │  │
│   └──────────┘  └──────────┘  └─────┬──────┘  └────────────┘  │
└─────────────────────────────────────┼───────────────────────────┘
                                      │ BullMQ Worker
                                      ▼
              ┌───────────────────────────────────────┐
              │         Flask ML Microservice          │
              │    (scikit-learn + Pandas + NumPy)    │
              │                                       │
              │  DataCleaner → FeatureEngineer →      │
              │  ModelSelector (LR vs RF) →           │
              │  TrendClassifier → ConfidenceScorer   │
              │                                       │
              │         Alpha Vantage API             │
              └───────────────────────────────────────┘

Request Flow — Order Matching

User Places Order → Node API → Redis Order Book → Matching Engine
→ Trade Recorded (MongoDB) → Portfolios Updated → Socket.IO Broadcast
→ All watching clients receive live update

Request Flow — ML Prediction

Premium User clicks Predict → Node API → BullMQ Queue
→ Worker calls Flask /predict → Model trains on real OHLCV data
→ Result stored in MongoDB → Socket.IO emits to user
→ PredictionChart.jsx renders Actual vs Predicted graph

✨ Features

🔐 Authentication System

  • Register / Login with JWT
  • Three roles: User, Premium, Admin
  • Role-based route protection on both backend and frontend
  • Password hashing with bcryptjs
  • JWT blacklist on logout via Redis

📊 Virtual Stock Market

  • Admin creates stocks with symbol, initial price, and volatility factor
  • Each stock tracks current price, volume, market cap, and full price history
  • Live price ticker scrolling across the top of the UI

⚡ Trading System

  • Market Orders — execute instantly at the best available price
  • Limit Orders — sit in the order book until a matching order arrives
  • Partial fills supported — if quantities don't match exactly, the remainder stays in the book
  • Cancel pending limit orders

📖 Order Book (Redis)

  • Buy orders sorted descending, sell orders sorted ascending
  • Stored in Redis sorted sets (orderbook:BUY:TECHX)
  • Top 10 bids and asks displayed live, updating via Socket.IO

🔧 Matching Engine

The core of TradeSphere. When highest buy price ≥ lowest sell price:

  1. Calculate executed price
  2. Reduce quantities on both orders
  3. Record Trade document in MongoDB
  4. Update both users' portfolios and cash balances
  5. Update stock's current price
  6. Emit Socket.IO events to all watching clients

🔴 Circuit Breaker

If a stock price moves more than 10% in 60 seconds:

  • Trading is automatically halted for 2 minutes
  • All new orders for that symbol are rejected
  • market:halted event broadcast to all clients
  • Mirrors real exchange halting logic (NSE, NYSE)

🤖 ML Predictions (Premium)

  • Next-day closing price prediction
  • Bullish / Bearish / Neutral trend classification
  • Confidence percentage (40–95%)
  • Actual vs Predicted graph
  • Auto-selects best model (Linear Regression vs Random Forest) by RMSE

📈 Portfolio System

  • Cash balance per user (default ₹1,00,000 virtual)
  • Stock holdings with average buy price
  • Unrealized P&L (live, updates with price)
  • Realized P&L (locked in after sell)
  • Full transaction history

🏆 Leaderboard

  • Top traders by total profit
  • Weekly ranking
  • Win rate percentage
  • Recalculated every 60 seconds via BullMQ scheduled job

🌐 Market Simulation

  • Every 5 seconds, stock prices fluctuate slightly based on volatility factor
  • Simulates real market movement even when no trades are happening
  • Handled by BullMQ repeatable job (never blocks the API)

🗂️ Tech Stack

| Layer | Technology | Purpose | |---|---|---| | Frontend | React 18 + Vite | UI framework | | Styling | Tailwind CSS | Utility-first CSS | | Charts | Chart.js | Candlestick + prediction graphs | | State | Redux Toolkit / Zustand | Global state management | | Real-time (FE) | Socket.IO Client | Live order book + trades | | HTTP Client | Axios | API calls | | Backend | Node.js + Express | REST API | | Real-time (BE) | Socket.IO | WebSocket server | | Database | MongoDB + Mongoose | Persistent storage | | Cache / Queue | Redis (ioredis) | Order book + price cache | | Job Queue | BullMQ | Background workers | | Auth | JWT + bcryptjs | Authentication | | ML Service | Python + Flask | Prediction microservice | | ML Models | scikit-learn | Linear Regression + Random Forest | | Data Processing | Pandas + NumPy | Feature engineering | | Market Data | Alpha Vantage API | Real OHLCV training data | | Deployment (FE) | Vercel | Frontend hosting | | Deployment (BE) | Railway | Backend + Redis + MongoDB | | Deployment (ML) | Render | ML microservice |


📁 Project Structure

tradesphere/
├── tradesphere-frontend/        # React app
│   ├── src/
│   │   ├── pages/               # Route-level components
│   │   ├── components/          # Feature components
│   │   │   ├── market/          # Stock cards, ticker, charts
│   │   │   ├── trading/         # Order form, order book, trade feed
│   │   │   ├── portfolio/       # Holdings, P&L, balance
│   │   │   ├── prediction/      # ML prediction UI (Premium)
│   │   │   ├── admin/           # Admin panel
│   │   │   └── ui/              # Reusable UI primitives
│   │   ├── hooks/               # Custom React hooks
│   │   ├── context/             # Auth, Socket, Theme contexts
│   │   ├── services/            # Axios API calls
│   │   ├── store/               # Redux/Zustand slices
│   │   └── utils/               # Formatters, helpers
│   └── ...
│
├── tradesphere-backend/         # Node.js API
│   ├── config/                  # DB, Redis, BullMQ setup
│   ├── models/                  # Mongoose schemas
│   ├── routes/                  # Express route definitions
│   ├── controllers/             # Route handlers
│   ├── middleware/              # Auth, role, rate limit
│   ├── services/                # Matching engine, order book, ML bridge
│   ├── queues/                  # BullMQ queue definitions
│   ├── workers/                 # BullMQ worker processors
│   └── utils/                   # JWT, logger, constants
│
└── tradesphere-ml/              # Flask ML microservice
    ├── routes/                  # /predict, /train, /health
    ├── models/                  # LinearModel, RandomForestModel, ModelSelector
    ├── preprocessing/           # DataCleaner, FeatureEngineer, Scaler
    ├── services/                # PredictionService, TrendClassifier, ConfidenceScorer
    ├── training/                # Train from Alpha Vanta

Related Skills

View on GitHub
GitHub Stars6
CategoryDevelopment
Updated8m ago
Forks0

Languages

JavaScript

Security Score

70/100

Audited on Mar 27, 2026

No findings