Skip to content

Asheesh18-codes/Order-Matching-Engine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Real-Time Order Matching Engine

A high-performance, distributed order matching and settlement system built with TypeScript, Node.js, Redis, and PostgreSQL. Processes 100+ orders per second with millisecond-level latency.

πŸ“‹ Table of Contents

Overview

This is a complete real-time trading exchange platform with:

  • Backend: High-performance order matching engine with async processing
  • Frontend: Interactive trading dashboard with live order books and portfolio management

Key Metrics

  • Throughput: 100+ orders/second
  • Trade Generation: ~140 orders/sec matched at 75%+ ratio
  • Latency: P99 < 1000ms at 100 concurrent users
  • Architecture: Async processing with Redis queues and worker threads

Architecture

System Design

Frontend (Next.js)
    ↓
REST API (Express) / WebSocket
    ↓
Redis Queues (order_queue, trade_queue)
    ↓
β”œβ”€ Matching Worker (Order Processing)
β”‚   └─ Matching Engine (Trade Generation)
β”‚       └─ Redis (trade_queue)
β”‚           ↓
β”‚       Settlement Worker (Trade Settlement)
β”‚           └─ PostgreSQL (Persistence)
β”‚               ↓
β”‚           Metrics Collector
β”‚
└─ WebSocket Server (Real-time Updates)

Components:

  • API Layer: RESTful endpoints for orders, authentication, and portfolio
  • Matching Engine: Price-time priority matching with side crossing validation
  • Settlement Service: ACID-compliant trade settlement with idempotency
  • Metrics System: Real-time performance tracking and throughput monitoring
  • WebSocket Server: Live order books and trade execution feeds

Data Flow

  1. User places order via REST API β†’ 202 ACCEPTED response
  2. Order queued to Redis order_queue
  3. Matching Worker consumes and processes orders
  4. Matched trades generated and published to trade_queue
  5. Settlement Worker batches and settles trades (50 trades or 15ms)
  6. Metrics and WebSocket updates sent to connected clients

Features

Trading Features

  • βœ… Limit orders with price-time priority matching
  • βœ… Buy/Sell side crossing validation
  • βœ… FIFO queue within same price level
  • βœ… ACID-compliant trade settlement
  • βœ… Idempotent order processing
  • βœ… Trade history and portfolio tracking

System Features

  • βœ… Real-time metrics dashboard
  • βœ… WebSocket live feeds
  • βœ… Rate limiting (API protection)
  • βœ… JWT authentication
  • βœ… Comprehensive error handling
  • βœ… Worker thread isolation

Quick Start

Prerequisites

  • Node.js 18+
  • PostgreSQL 14+
  • Redis 7+

Installation

# Clone repository
git clone <repo-url>
cd order-matching-engine

# Backend setup
cd backend
npm install
cp .env.example .env
# Update .env with your database and Redis URLs

# Run migrations
npx prisma migrate dev

# Start backend
npm run dev

# Frontend setup (in new terminal)
cd frontend
pnpm install
npm run dev

Environment Variables

Backend (.env):

DATABASE_URL=postgresql://user:password@localhost:5432/trading_db
REDIS_URL=redis://localhost:6379
NODE_ENV=development
PORT=8000

Frontend (.env.local):

NEXT_PUBLIC_API_URL=http://localhost:8000
NEXT_PUBLIC_WS_URL=ws://localhost:8000

Run Load Test

cd backend
npm run loadtest 50 30  # 50 users, 30 seconds

Project Structure

order-matching-engine/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ index.ts              # Express server & worker management
β”‚   β”‚   β”œβ”€β”€ api/                  # REST endpoints
β”‚   β”‚   β”œβ”€β”€ auth/                 # Authentication
β”‚   β”‚   β”œβ”€β”€ services/             # Business logic
β”‚   β”‚   β”œβ”€β”€ worker/               # Worker threads
β”‚   β”‚   β”œβ”€β”€ queue/                # Redis queue management
β”‚   β”‚   β”œβ”€β”€ realtime/             # WebSocket server
β”‚   β”‚   β”œβ”€β”€ middleware/           # Express middleware
β”‚   β”‚   └── monitoring/           # Metrics collection
β”‚   β”œβ”€β”€ prisma/
β”‚   β”‚   β”œβ”€β”€ schema.prisma         # Database schema
β”‚   β”‚   └── migrations/           # Database migrations
β”‚   β”œβ”€β”€ tests/
β”‚   β”‚   └── loadTest.ts           # Load testing script
β”‚   └── package.json
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ page.tsx              # Home page
β”‚   β”‚   β”œβ”€β”€ login/                # Authentication
β”‚   β”‚   β”œβ”€β”€ dashboard/            # Trading dashboard
β”‚   β”‚   └── layout.tsx            # Root layout
β”‚   β”œβ”€β”€ components/               # React components
β”‚   β”œβ”€β”€ lib/                      # Utilities
β”‚   └── package.json
β”‚
β”œβ”€β”€ README.md                     # This file
β”œβ”€β”€ ARCHITECTURE.md               # System design details
└── DEVELOPMENT.md                # Developer guide

Performance

Load Test Results (100 users, 30 seconds)

Metric Value
Orders Placed 3,980
Throughput 100.42 orders/sec
Trades Executed 14,787
Avg Latency 454.92 ms
P95 Latency 751 ms
P99 Latency 993 ms
Success Rate 100%

Performance Characteristics

  • Order Processing: 100+ orders/second
  • Trade Matching: 75%+ of orders match (depends on price crossing)
  • Settlement: Batched every 50 trades or 15ms
  • Queue Latency: <50ms average
  • Database Writes: Batched for efficiency

Documentation

Contributing

  1. Create a feature branch: git checkout -b feature/your-feature
  2. Make your changes and test thoroughly
  3. Run load tests: npm run loadtest
  4. Submit a pull request

Development Commands

Backend:

npm run dev           # Start with ts-node
npm run build         # Build TypeScript
npm run loadtest      # Run load test (default: 50 users, 60s)
npm test              # Run tests
npx prisma studio    # Open database UI

Frontend:

npm run dev           # Start dev server
npm run build         # Build for production
npm run lint          # Run ESLint

API Endpoints

Authentication

  • POST /auth/register - User registration
  • POST /auth/login - User login
  • POST /auth/logout - User logout

Orders

  • POST /orders - Place new order
  • GET /orders - Get user's orders
  • GET /orders/:id - Get specific order

Portfolio

  • GET /portfolio - Get user portfolio

Metrics

  • GET /metrics - System performance metrics

See API_ROUTES.md for detailed endpoint documentation.

License

MIT

Support

For issues and questions, please open an issue on the repository.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published