Skip to content

About

High-performance limit order book / matching engine in Rust — price-time priority, REST API + realtime WebSocket market data

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

Repository files navigation

Rust Orderbook

A high-performance, production-ready limit order book implementation in Rust with a REST API and WebSocket support.

Features

  • ✅ Full Order Matching Engine - Price-time priority matching algorithm
  • ✅ Order Management - Create, cancel, and query orders
  • ✅ Real-time Updates - WebSocket support for market data (depth, trades, ticker)
  • ✅ Trade History - Complete trade tracking and history
  • ✅ Market Data - Real-time market depth, ticker, and statistics
  • ✅ Web UI - Modern HTML interface for easy interaction
  • ✅ Simulation - Built-in market simulation tool
  • ✅ API Documentation - Interactive Swagger UI for API exploration
  • ✅ Type Safety - Leverages Rust's type system for correctness
  • ✅ Concurrent - Thread-safe with Arc
  • ✅ Logging - Structured logging with tracing

Quick Start

Prerequisites

Installation

# Clone the repository
git clone <your-repo-url>
cd rs-orderbook

# Build the project
cargo build --release

# Run the server
cargo run

The server will start on http://127.0.0.1:8080 by default.

Running the Simulation

The project includes a market simulation tool that generates random orders to demonstrate the matching engine.

# Run the simulation in a separate terminal
cargo run --example simulation

Configuration

Set environment variables to configure the server:

export HOST=0.0.0.0
export PORT=8080
export RUST_LOG=info  # Options: trace, debug, info, warn, error

Using the Web Interface

Once the server is running, open your browser to:

http://127.0.0.1:8080

The web interface provides:

  • Order Creation - Place buy and sell orders
  • Order Cancellation - Cancel existing orders
  • Market Depth - View current bids and asks
  • Trade History - See recent trades
  • Market Ticker - Real-time market statistics
  • Real-time Updates - Live data via WebSockets

API Documentation

Interactive Swagger UI documentation is available at:

http://127.0.0.1:8080/docs/

API Reference

Base URL

http://localhost:8080

Endpoints

Health Check

GET /health

Response:

{
  "status": "healthy",
  "timestamp": "2026-02-08T16:30:00Z",
  "total_orders": 42,
  "total_trades": 15
}

Create Order

POST /order
Content-Type: application/json

Request Body:

{
  "price": 100.0,
  "quantity": 10.0,
  "user_id": 1,
  "side": "BUY"  // or "SELL"
}

Response:

{
  "order_id": 1,
  "filled_quantity": 5.0,
  "status": "PartiallyFilled",
  "trades": [
    {
      "trade_id": 1,
      "price": "100",
      "quantity": 5.0,
      "timestamp": "2026-02-08T16:30:00Z"
    }
  ]
}

Cancel Order

DELETE /order
Content-Type: application/json

Request Body:

{
  "order_id": 1
}

Get User Balance

GET /balance/{user_id}

Response:

{
  "user_id": 1,
  "btc": "10",
  "usdt": "10000"
}

Get Order Details

GET /order/{order_id}

Get User Orders

GET /orders/user/{user_id}

Get Trade History

GET /trades?limit=10

Get Market Depth

GET /depth

Response:

{
  "bids": [
    ["100", "50"],  // [price, quantity]
    ["99", "100"]
  ],
  "asks": [
    ["101", "75"],
    ["102", "25"]
  ],
  "last_updated": "2026-02-08T16:30:00Z"
}

Get Ticker

GET /ticker

Response:

{
  "last_price": "100",
  "volume_24h": 1000.0,
  "high_24h": "105",
  "low_24h": "95",
  "price_change_24h": "5",
  "num_trades": 42
}

WebSocket API

Connect to the WebSocket endpoint for real-time updates:

ws://127.0.0.1:8080/ws

Messages

The server broadcasts the following message types:

1. Depth Update

{
  "type": "depth",
  "data": {
    "bids": [["100", "50"]],
    "asks": [["101", "20"]],
    "last_updated": "..."
  }
}

2. Trade Update

{
  "type": "trade",
  "data": {
    "trade_id": 123,
    "price": "100.5",
    "quantity": 10.0,
    "timestamp": "..."
  }
}

3. Ticker Update

{
  "type": "ticker",
  "data": {
    "last_price": "100.5",
    "volume_24h": 5000.0,
    "price_change_24h": "1.5",
    ...
  }
}

4. Heartbeat Send ping string to keep connection alive. Server responds with:

{ "type": "pong", "data": null }

Architecture

Order Matching Algorithm

The orderbook implements price-time priority matching:

  1. Price Priority: Orders are matched at the best available price.
  2. Time Priority: Orders at the same price level are matched FIFO.

Data Structures

  • BTreeMap for price levels (automatic sorting).
  • VecDeque for orders at each price level (FIFO queue).
  • HashMap for fast order lookup by ID.

Concurrency

The orderbook uses Arc<Mutex<Orderbook>> for thread-safe access across multiple HTTP requests and WebSocket connections.

Development

Running Tests

cargo test

Code Quality

cargo fmt
cargo clippy

Future Enhancements

  • Persistence layer (PostgreSQL/Redis)
  • Order types (market orders, stop-loss, limit FOK/IOC)
  • Multiple trading pairs
  • Rate limiting per user
  • Authentication and Authorization
  • Docker containerization

License

MIT

About

High-performance limit order book / matching engine in Rust — price-time priority, REST API + realtime WebSocket market data

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages