Skip to content

PrajwalGraj/CEX-rust

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CEX - rust

A Rust-based centralized exchange (CEX) simulator built to explore systems programming concepts such as asynchronous actor-based architecture, order matching, balance management, transactional persistence, and recovery.

The project focuses on the core backend components of a spot exchange.

Architecture

alt text

Benchmarks

latency benchmarks measured over 100 iterations.

  • Place Order : ~ 2.419 ms
  • Match Order : ~ 2.713 ms
  • Cancel Order: ~ 1.400 ms

Place Order

Place Order

Place Order

Project Structure

crates
├── api (REST API and HTTP routes)
│
├── balance (Balance manager and reservation logic)
│
├── benchmark (End-to-end benchmark runner)
│
├── domain (Shared domain models)
│
├── engine (Matching engine and order book)
│
├── exchange (Actors and exchange orchestration)
│
└── storage (PostgreSQL repositories)

Features

  • Price-Time Priority (FIFO) matching engine
  • Limit and Market (IOC) orders
  • Partial and complete order fills
  • Balance reservation and release
  • Atomic settlement
  • PostgreSQL persistence
  • Recovery on restart
  • REST API
  • Order cancellation
  • End-to-end latency benchmarking

Tech Stack

  • Rust
  • Tokio
  • Axum
  • SQLx
  • PostgreSQL
  • Serde

Matching Engine

Uses Price-Time Priority (FIFO) matching with a BTreeMap for price levels and a VecDeque for FIFO execution within each price level.

Supported Orders

  • Limit
  • Market (IOC)

Supported Operations

  • Full fills
  • Partial fills
  • Multiple maker matches
  • Order cancellation

Persistence & Recovery

Exchange state is persisted in PostgreSQL. Settlement is executed atomically using a PostgreSQL transaction to ensure consistency across balances, orders, and trades.

REST API

Deposit Funds

POST /deposit

Place Order

POST /orders

Cancel Order

POST /orders/{order_id}/cancel

Get Balances

GET /balances/{user_id}

Get Order Book

GET /book/{market}

Running Locally

Clone the repository

git clone https://github.com/<your-username>/CEX-rust.git

cd CEX-rust

Start PostgreSQL

Update your .env file with the database connection.

DATABASE_URL=postgres://postgres:password@localhost/cexrust

Run migrations:

cargo sqlx migrate run

Start the API

cargo run -p api

Run benchmarks

cargo run -p benchmark -- place

cargo run -p benchmark -- match

cargo run -p benchmark -- cancel

License

MIT

About

A rust-based centralized exchange (CEX) featuring actor-based architecture, price-time priority matching, and transactional settlement.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages