Skip to content

A smart order router that compares prices across multiple crypto exchanges (Raydium & Meteora), picks the best one, executes trades with real-time updates via WebSocket, and handles multiple orders concurrently using a queue system.

Notifications You must be signed in to change notification settings

may-tas/order-execution-engine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

30 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

DEX Order Execution Engine

High-performance order execution engine with multi-DEX routing and real-time WebSocket updates for Solana. Uses mock DEX implementation with realistic delays and price variations.

๐ŸŒ Live API: https://order-execution-engine-production-fa00.up.railway.app | ๐Ÿ“ฎ Postman: Collection | ๐Ÿ“บ Demo: Youtube


๐Ÿ› ๏ธ Tech Stack

Category Technologies
Backend Node.js, TypeScript, Fastify
Database PostgreSQL (Prisma ORM), Redis
Queue BullMQ
WebSocket @fastify/websocket
Validation Zod
Testing Integration & E2E tests
Dev Tooling Docker Compose, ESLint, Winston Logger

๐Ÿ—๏ธ Architecture

Clean Architecture + Repository Pattern

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   HTTP/WS API   โ”‚  โ† Fastify routes
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  Controllers    โ”‚  โ† Request handlers
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   Services      โ”‚  โ† Business logic (DEX, Orders, Queue, WebSocket)
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  Repositories   โ”‚  โ† Data access (Database, Redis)
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ PostgreSQL/Redisโ”‚  โ† Persistent storage
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Order Processing Flow:

API Request โ†’ Validation โ†’ Queue (BullMQ) โ†’ Worker โ†’ DEX Router โ†’ Execution โ†’ WebSocket Broadcast

Implementation: Mock DEX providers (Option B) - simulates Raydium/Meteora with realistic delays (2-3s) and price variations (~2-5%). Focus on architecture and flow rather than real devnet execution.


๐Ÿ“ Project Structure

src/
โ”œโ”€โ”€ server.ts                # Main entry point
โ”œโ”€โ”€ config/                  # Environment config
โ”œโ”€โ”€ controllers/             # Request handlers (health, orders)
โ”œโ”€โ”€ routes/                  # API route definitions
โ”œโ”€โ”€ services/
โ”‚   โ”œโ”€โ”€ dex/                # DEX providers (Raydium, Meteora) + routing
โ”‚   โ”œโ”€โ”€ orders/             # Order management & lifecycle
โ”‚   โ”œโ”€โ”€ queue/              # BullMQ queue + worker
โ”‚   โ””โ”€โ”€ websocket/          # WebSocket manager (subscriptions, broadcasts)
โ”œโ”€โ”€ repositories/           # Database/Redis access layer
โ”œโ”€โ”€ validators/             # Zod schemas
โ”œโ”€โ”€ types/                  # TypeScript types
โ””โ”€โ”€ utils/                  # Logger, helpers

prisma/
โ”œโ”€โ”€ schema.prisma           # Database schema
โ””โ”€โ”€ migrations/             # SQL migrations

tests/
โ”œโ”€โ”€ integration/            # Service-level tests (no server)
โ””โ”€โ”€ e2e/                    # Full API tests (with server)

๐Ÿš€ Installation

Prerequisites

  • Node.js โ‰ฅ18.0.0
  • Docker & Docker Compose
  • pnpm v10+ (install with npm install -g pnpm)

Setup Steps

1. Clone the repository

git clone <repository-url>
cd order-execution-engine

2. Install dependencies

pnpm install

3. Configure environment

cp .env.example .env
# Edit .env with your database credentials if needed

4. Start services (PostgreSQL & Redis)

pnpm docker:up

5. Run database migrations

pnpm db:migrate

6. Start the server

pnpm dev
# Server runs at http://localhost:3000

7. Verify installation

curl http://localhost:3000/health
# Should return: {"status":"ok","timestamp":...}

โšก Quick Start

pnpm install              # Install dependencies
pnpm docker:up            # Start PostgreSQL & Redis
pnpm db:migrate           # Run migrations
pnpm dev                  # Start server (http://localhost:3000)

๐Ÿ“ก API Endpoints

Health

Method Endpoint Description
GET /health Basic health check
GET /health/status Detailed system status
GET /health/websocket WebSocket stats
GET /health/queue Queue statistics

Orders

Method Endpoint Description
POST /api/orders/execute Execute market order
POST /api/orders/simulate Simulate order (dry-run)
GET /api/orders/:orderId Get order status
GET /api/orders/stats Order statistics

WebSocket

Protocol Endpoint Description
WS /ws Real-time order updates (subscribe to orderId or * for all)

Note: WebSocket uses standard GET-based upgrade handshake (RFC 6455). POST requests cannot be upgraded to WebSocket on the same connection. Use separate POST for order execution, then connect via WebSocket for updates.


๐Ÿ’ก Example Usage

Execute Order

curl -X POST http://localhost:3000/api/orders/execute \
  -H "Content-Type: application/json" \
  -d '{
    "type": "MARKET",
    "tokenIn": "SOL",
    "tokenOut": "USDC",
    "amountIn": 2.0,
    "slippage": 0.01
  }'

WebSocket Subscribe

const ws = new WebSocket('ws://localhost:3000/ws');

ws.onopen = () => {
  ws.send(
    JSON.stringify({
      type: 'subscribe',
      payload: { orderId: '*' },
    })
  );
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Order status:', data);
  // Receive: PENDING โ†’ ROUTING โ†’ BUILDING โ†’ SUBMITTED โ†’ CONFIRMED
};

๐Ÿ”„ Order Lifecycle

PENDING โ†’ ROUTING โ†’ BUILDING โ†’ SUBMITTED โ†’ CONFIRMED โœ…
   โ†“         โ†“          โ†“           โ†“
 Queue   DEX Price  Build Tx   Send Tx
         (200ms)                 โ†“
                              FAILED โŒ
                           (on error)

Orders can fail at any stage (routing, building, submission) and transition directly to FAILED status.


๐Ÿงช Testing

Run All Tests

# Integration tests (no server needed)
pnpm test:all:integration
# E2E tests (server must be running)
pnpm dev                  # Terminal 1
pnpm test:all:e2e         # Terminal 2

Individual Tests

pnpm test:db              # Database & Redis
pnpm test:dex             # DEX routing
pnpm test:queue           # Queue processing
pnpm test:orders          # Order service
pnpm test:websocket       # WebSocket real-time
pnpm test:api             # API endpoints
pnpm test:integration     # Full integration

๐Ÿ“‹ Commands

Development

pnpm dev                  # Start with hot reload
pnpm build                # Build for production
pnpm start                # Run production build

Database

pnpm db:migrate           # Run migrations
pnpm db:push              # Push schema changes
pnpm db:studio            # Open Prisma Studio

Docker

pnpm docker:up            # Start PostgreSQL & Redis
pnpm docker:down          # Stop services
pnpm docker:logs          # View logs

Code Quality

pnpm lint                 # Check issues
pnpm lint:fix             # Auto-fix issues
pnpm format               # Format code

โœจ Features

  • โœ… Multi-DEX routing (Raydium, Meteora)
  • โœ… Real-time WebSocket updates
  • โœ… BullMQ queue with retries
  • โœ… 10 concurrent order processing
  • โœ… Health monitoring endpoints
  • โœ… Zod validation
  • โœ… PostgreSQL + Redis
  • โœ… Docker Compose setup
  • โœ… Integration & E2E tests

๐Ÿ“ฆ Requirements

  • Node.js โ‰ฅ18.0.0
  • PostgreSQL 14+
  • Redis 6+
  • pnpm v10+

About

A smart order router that compares prices across multiple crypto exchanges (Raydium & Meteora), picks the best one, executes trades with real-time updates via WebSocket, and handles multiple orders concurrently using a queue system.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages