Skip to content

Repository files navigation

CEX — High-Performance Cryptocurrency Exchange Platform

TypeScript React Node.js Prisma Tailwind CSS PNPM

CEX is a full-stack, enterprise-grade Centralized Cryptocurrency Exchange platform built with a high-throughput microservices architecture. It features an in-memory orderbook matching engine using price-time priority algorithm, low-latency Redis Pub/Sub inter-process messaging, real-time WebSocket orderbook depth streaming, PostgreSQL persistence via Prisma ORM, and a responsive React frontend with interactive Lightweight Charts.


🏗️ Architecture & How It Works

The platform operates as a modular monorepo divided into focused services:

[ Client Browser ]
      │
      ├─── REST HTTP API ─────► [ Backend Gateway (Express.js) ] ───► [ Neon PostgreSQL ]
      │                                    │
      └─── WebSocket Stream ◄───────┐      │ (Order Requests via Redis Queue)
                                    │      ▼
                             [ Upstash Redis Pub/Sub ]
                                    ▲
                                    │ (Matches / Trade Executions)
                                    │
                     [ Matching Engine (In-Memory Orderbook) ]

Order Lifecycle & Execution Flow:

  1. Order Submission: User places a Limit or Market order via the frontend interface.
  2. Validation & Balance Lock: The Backend API validates request parameters (Zod schemas), authenticates JWT tokens, and locks required user funds in PostgreSQL inside a database transaction.
  3. Queueing: The Backend pushes the validated order payload into the Redis order_events queue.
  4. Orderbook Matching: The standalone Matching Engine consumes events sequentially, updating its in-memory Price-Time Priority Orderbook (Bids / Asks priority heaps).
  5. Trade Execution: When orders overlap, trades are instantly executed, generating trade execution records and balance settlements.
  6. Real-time Broadcast: Trade events and depth updates are published to Redis channels. The WebSocket service broadcasts live snapshots to connected trading charts and orderbook UI components instantly.

✨ Key Features

  • In-Memory Orderbook Matching Engine: Sub-millisecond order matching supporting LIMIT and MARKET order types with price-time priority.
  • 📊 Real-time Trading Interface: Interactive candlestick price charts powered by TradingView's lightweight-charts, depth orderbook, live order history, and active position management.
  • 🔒 Secure Balance Management: Atomic database transactions ensuring zero double-spending or balance drift during active order placements.
  • 📡 Live WebSocket Feeds: Real-time orderbook depth snapshots, trade execution notifications, and live ticker price updates.
  • 💼 Simulated Wallet Deposit: Built-in test asset faucet for quick paper-trading and testing.
  • 🎨 Modern Dark Aesthetics: Premium UI design with glassmorphism, responsive navigation, and intuitive order entry widgets.

📁 Repository Structure

CEX/
├── Backend/
│   ├── apps/
│   │   ├── backend/        # Express.js REST API Gateway, Auth, & WebSocket server
│   │   └── engine/         # High-speed In-Memory Orderbook Matching Engine
│   └── packages/
│       ├── common/         # Shared backend utilities & Redis queue abstractions
│       └── types/          # Shared TypeScript type definitions
├── frontend/               # React + Vite + Tailwind CSS trading web application
├── learning/               # Engineering design documentation & system specs
├── .env.example            # Environment variable setup template
├── pnpm-workspace.yaml     # PNPM Monorepo configuration
└── README.md               # Project overview & guide

🚀 Getting Started

Prerequisites

  • Node.js: v18.0.0 or higher
  • PNPM: v8.0.0 or higher (npm install -g pnpm)
  • PostgreSQL: Local instance or Cloud DB (e.g. Neon PostgreSQL)
  • Redis: Local Redis or Cloud Redis (e.g. Upstash Redis)

Installation & Configuration

  1. Clone the repository:

    git clone https://github.com/Lkshayyadav/CEX.git
    cd CEX
  2. Install dependencies:

    pnpm install
  3. Configure Environment Variables: Copy .env.example to .env in frontend/ and Backend/apps/backend/:

    cp .env.example frontend/.env
    cp .env.example Backend/apps/backend/.env

    Update the credentials in Backend/apps/backend/.env:

    DATABASE_URL="postgresql://user:password@host:5432/dbname?sslmode=require"
    REDIS_URL="rediss://default:password@host.upstash.io:6379"
    PORT=3000
    JWT_SECRET="your-super-secret-jwt-key"
    CORS_ALLOWED_ORIGINS="http://localhost:5173"
  4. Initialize Database: Generate Prisma client and push the schema to PostgreSQL:

    pnpm --filter @cex/backend prisma:generate
    pnpm --filter @cex/backend prisma:db-push

Running Locally

To run all monorepo microservices concurrently (Frontend, Backend API, & Matching Engine):

pnpm dev
  • Frontend Application: http://localhost:5173
  • Backend API Gateway: http://localhost:3000/api/v1
  • WebSocket Gateway: ws://localhost:3000

🔑 REST API Reference

Method Endpoint Description Auth Required
POST /api/v1/auth/register Register a new user account
POST /api/v1/auth/login Authenticate user & receive JWT
GET /api/v1/markets Get supported trading pairs
GET /api/v1/markets/:symbol/depth Get current orderbook depth snapshot
GET /api/v1/markets/:symbol/klines Fetch historical candlestick chart data
POST /api/v1/orders Submit a new BUY / SELL order
DELETE /api/v1/orders/:id Cancel an active open order
GET /api/v1/orders/open Fetch current user's open orders
GET /api/v1/balances Fetch user token balances
POST /api/v1/balances/deposit Deposit simulated funds for testing

🧑‍💻 Author & Social Links

Built by Lakshay Yadav.


📜 License

This project is licensed under the MIT License.

About

⚡ High-frequency centralized crypto exchange trading terminal with in-memory matching engine (<0.4ms latency), real-time order books & WebSockets.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages