Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Exchange Assignment

A high-performance, real-time cryptocurrency exchange matching engine built with FastAPI and Python. This system implements a complete order book with multiple order types, real-time WebSocket feeds, and price-time priority matching.

Features

  • Multiple Order Types

    • Market Orders: Execute immediately at best available price
    • Limit Orders: Execute at specified price or better, remainder stays in book
    • IOC (Immediate-or-Cancel): Execute immediately, cancel unfilled portion
    • FOK (Fill-or-Kill): Execute completely or cancel entirely
  • Real-time Market Data

    • WebSocket feed for L2 order book snapshots (top 10 levels)
    • WebSocket feed for trade executions
    • Snapshot updates every 100ms for changed symbols
  • Price-Time Priority Matching

    • Best price gets matched first
    • Orders at same price level matched by time (FIFO)
    • Efficient matching using sorted dictionaries and priority queues
  • Supported Symbols

    • BTC, ETH, USDT, SOL

Architecture

The system follows an event-driven architecture with asynchronous task processing:

Architecture Diagram

Core Components

  • MatchingEngine: Core matching logic for all order types
  • OrderBook: Maintains bid/ask queues with price-time priority
  • Publisher: Broadcasts trade executions and order book updates
  • WebSocket Endpoints: Real-time data feeds to clients

Getting Started

Prerequisites

  • Python 3.12 or higher
  • uv package manager (recommended)
  • Docker (optional, for containerized deployment)

Installation

  1. Clone the repository:
git clone <repository-url>
cd exchange-assignment
  1. Install dependencies using uv:
uv sync

Or using pip:

pip install -r requirements.txt
  1. Create a .env file in the root directory:
HOST=0.0.0.0
PORT=8000

Running the Application

Local Development

uv run main.py

Or:

python main.py

The server will start on http://localhost:8000

Using Docker

docker-compose up --build

API Reference

REST Endpoints

Health Check

GET /health

Returns server health status.

Response:

{
  "message": "OK"
}

Create Order

POST /v1/orders

Submit a new order to the matching engine.

Request Body:

{
  "type": "limit",
  "symbol": "BTC",
  "side": "buy",
  "quantity": "1.5",
  "price": "50000.00"
}

Parameters:

  • type (string): Order type - market, limit, ioc, or fok
  • symbol (string): Trading symbol - BTC, ETH, USDT, or SOL
  • side (string): Order side - buy or sell
  • quantity (decimal): Order quantity (must be > 0)
  • price (decimal): Limit price (required for limit/ioc/fok, optional for market)

Response:

{
  "message": "order created",
  "order_id": "123e4567-e89b-12d3-a456-426614174000"
}

WebSocket Endpoints

Market Data Feed

WS /v1/ws/market-data

Subscribe to real-time order book snapshots (L2 data).

Message Format:

{
  "timestamp": "2025-10-08T12:34:56.789",
  "symbol": "BTC",
  "bids": [
    ["50000.00", "1.5"],
    ["49999.00", "2.3"]
  ],
  "asks": [
    ["50001.00", "0.8"],
    ["50002.00", "1.2"]
  ]
}

Trade Execution Feed

WS /v1/ws/trades

Subscribe to real-time trade executions.

Message Format:

{
  "timestamp": "2025-10-08T12:34:56.789",
  "symbol": "BTC",
  "trade_id": "987f6543-e21b-43c1-b123-987654321000",
  "price": "50000.00",
  "quantity": "1.5",
  "aggressor_side": "buy",
  "maker_order_id": "123e4567-e89b-12d3-a456-426614174000",
  "taker_order_id": "234e5678-e89b-12d3-a456-426614174001"
}

Order Matching Logic

Market Orders

  1. Match against best available prices on opposite side
  2. Continue matching until fully filled or no liquidity
  3. Status: filled or partially_filled/cancelled if liquidity exhausted

Limit Orders

  1. Match against acceptable prices (buy at ≤ limit, sell at ≥ limit)
  2. Unfilled quantity added to order book
  3. Status: filled, partially_filled, or pending

IOC Orders

  1. Match immediately at acceptable prices
  2. Cancel any unfilled quantity (never sits in book)
  3. Status: filled, partially_filled, or cancelled

FOK Orders

  1. Check if full quantity can be filled before executing
  2. Either fill completely or cancel entirely
  3. Status: filled or cancelled

Project Structure

exchange-assignment/
├── app/
│   ├── core/
│   │   └── settings.py          # Application configuration
│   ├── model/
│   │   ├── order.py             # Order data models
│   │   ├── order_book.py        # OrderBook implementation
│   │   ├── order_book_factory.py # Factory for managing multiple order books
│   │   └── trade_execution.py   # Trade execution data model
│   ├── routes/
│   │   └── v1/
│   │       └── endpoints/
│   │           └── main.py      # API endpoints
│   ├── services/
│   │   ├── matching_engine.py   # Core matching logic
│   │   └── publisher.py         # WebSocket message publisher
│   ├── dependencies.py          # FastAPI dependencies
│   └── server.py                # FastAPI application setup
├── Dockerfile
├── docker-compose.yml
├── main.py                      # Application entry point
├── pyproject.toml              # Project dependencies
└── README.md

Technology Stack

  • FastAPI: High-performance async web framework
  • Pydantic: Data validation and settings management
  • sortedcontainers: Efficient sorted data structures for order books
  • uvicorn: ASGI server
  • WebSockets: Real-time bidirectional communication

Performance Considerations

  • Async I/O: Non-blocking operations throughout the stack
  • Efficient Data Structures: SortedDict for O(log n) price level operations
  • Lazy Cleanup: Cancelled orders marked in-place to avoid queue reorganization
  • Snapshot Optimization: Only generates snapshots for symbols with changes
  • Queue-based Architecture: Decouples order submission from matching

Development

Code Style

The project follows Python best practices:

  • Type hints throughout
  • Pydantic models for data validation
  • Async/await for concurrency
  • Clear separation of concerns

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages