Skip to content

Latest commit

 

History

History
237 lines (168 loc) · 5.63 KB

File metadata and controls

237 lines (168 loc) · 5.63 KB

Cryptocurrency Exchange Platform

A high-performance, real-time cryptocurrency exchange platform built with a microservices architecture. Features include order matching, real-time market data, WebSocket connections, and a modern trading interface.

Architecture

image

Screenshot 2024-06-29 at 3 52 33 PM

📋 Prerequisites

  • Node.js
  • Docker and Docker Compose
  • Redis
  • PostgreSQL with TimescaleDB extension

💡 Technical Decisions

Why an in-memory order book?

Order matching needs to be fast — microseconds, not milliseconds. Storing orders directly in a database would add network + disk I/O on every match, making it impossible to handle high throughput. The engine keeps the full order book in memory and only persists completed trades asynchronously via a Redis queue to the DB processor service. This decoupling is what allows the engine to handle 10,000+ orders/sec without being bottlenecked by the database.

Why TimescaleDB over plain PostgreSQL?

Candlestick (kline) data is pure time-series — every query is "give me all prices between time A and time B." TimescaleDB's hypertables partition this data automatically by time, cutting kline query times dramatically compared to a regular Postgres table with billions of rows. The 1m/1h/1w materialized views are pre-aggregated, so the frontend gets instant responses without re-scanning raw trade data on every request.

Why a separate WebSocket service?

Market data needs to be broadcast to potentially thousands of connected clients simultaneously. If the WebSocket logic lived inside the API server, a spike in connected users would compete with order processing for the same resources. Separating it means the trading engine is completely isolated from broadcast load — the WS server just subscribes to Redis pub/sub and forwards updates.

Why Redis as the message bus?

Each service (API, engine, DB processor, WS server) needs to communicate without being directly coupled. Redis pub/sub gives a lightweight, fast message bus that keeps services independent. The API publishes an order → engine picks it up → publishes the result → DB processor and WS server both consume it. Adding or restarting any single service doesn't affect the others.

🚀 Quick Start

1. Clone the Repository

git clone https://github.com/akash-wt/exchange
cd exchange

2. Start Infrastructure Services

cd Backend/docker
docker-compose up -d

This starts:

  • TimescaleDB on port 5432
  • Redis on port 6379

3. Initialize Database

cd Backend/db
npm install
npm run seed:db

4. Start Backend Services

API Server:

cd Backend/api
npm install
npm run dev

Trading Engine:

cd Backend/engine
npm install
npm run dev

Database Processor:

cd Backend/db
npm install
npm run dev

WebSocket Server:

cd Backend/ws
npm install
npm run dev

Market Maker (Optional):

cd Backend/mm
npm install
npm run dev

5. Start Frontend

cd frontend
npm install
npm run dev

📁 Project Structure

├── Backend/
│   ├── api/           # REST API server
│   ├── engine/        # Trading engine
│   ├── db/            # Database service
│   ├── ws/            # WebSocket server
│   ├── mm/            # Market maker
│   └── docker/        # Infrastructure setup
├── frontend/          # React frontend
└── README.md

Configuration

Environment Variables

Each service uses environment variables for configuration. Key variables include:

  • Database connection settings
  • Redis connection details
  • API endpoints
  • WebSocket URLs

Database Schema

The platform uses TimescaleDB for efficient time-series data storage:

  • tata_prices: Price and volume data
  • klines_1m/1h/1w: Materialized views for different timeframes

📊 API Endpoints

Orders

  • POST /api/v1/order - Place new order
  • DELETE /api/v1/order - Cancel order
  • GET /api/v1/order/open - Get open orders

Market Data

  • GET /api/v1/depth - Order book depth
  • GET /api/v1/trades - Recent trades
  • GET /api/v1/tickers - Market tickers
  • GET /api/v1/klines - Historical price data

🔄 WebSocket Streams

Subscribe to real-time data streams:

// Depth updates
{"method": "SUBSCRIBE", "params": ["depth@TATA_INR"]}

// Trade updates
{"method": "SUBSCRIBE", "params": ["trade@TATA_INR"]}

// Ticker updates
{"method": "SUBSCRIBE", "params": ["ticker@TATA_INR"]}

Testing

Run the test suite:

cd Backend/engine
npm test

Tests cover:

  • Order matching logic
  • Market depth calculations
  • Trade execution scenarios

🚀 Deployment

Production Considerations

  1. Database: Use managed PostgreSQL with TimescaleDB
  2. Redis: Use Redis Cluster for high availability
  3. Load Balancing: Deploy multiple API instances behind a load balancer
  4. Monitoring: Implement comprehensive logging and monitoring
  5. Security: Add authentication, rate limiting, and input validation

Docker Deployment

Build and deploy using Docker:

# Build services
docker build -t exchange-api ./Backend/api
docker build -t exchange-engine ./Backend/engine
docker build -t exchange-ws ./Backend/ws

# Deploy with docker-compose
docker-compose up -d

Note: This is a development/educational project. For production use, additional security measures, testing, and compliance considerations are required.