Skip to content

iwtxokhtd83/MatchEngine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MatchEngine

A high-performance order matching engine written in Go.

Features

  • Limit and market order support
  • Time-in-force: GTC (default), IOC (Immediate-or-Cancel), FOK (Fill-or-Kill)
  • Stop orders: Stop-Market and Stop-Limit with automatic trigger on last trade price
  • Price-time priority matching (FIFO)
  • Exact decimal arithmetic via shopspring/decimal
  • Efficient price-level order book with O(log p) insertion (p = distinct price levels)
  • Duplicate order ID detection
  • Internal order ID generation (atomic counter, monotonically increasing)
  • Self-trade prevention (4 modes: CancelResting, CancelIncoming, CancelBoth, Decrement)
  • Thread-safe design with snapshot-based order book reads
  • Bounded trade log with configurable size and trade callback
  • Symbol validation and normalization

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Order Input │────▢│ Match Engine │────▢│   Trades    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  Order Book  β”‚
                    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
                    β”‚  Bids (Buy)  β”‚
                    β”‚  Asks (Sell) β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Getting Started

Prerequisites

  • Go 1.21+

Build

go build ./...

Test

go test ./... -v

Run Example

go run cmd/example/main.go

Project Structure

.
β”œβ”€β”€ pkg/
β”‚   β”œβ”€β”€ engine/       # Core matching engine
β”‚   β”œβ”€β”€ orderbook/    # Order book implementation
β”‚   └── model/        # Order, Trade, and other models
β”œβ”€β”€ cmd/
β”‚   └── example/      # Example usage
β”œβ”€β”€ go.mod
└── README.md

How It Works

The engine uses a price-time priority algorithm:

  1. Buy orders are sorted by price descending, then by time ascending
  2. Sell orders are sorted by price ascending, then by time ascending
  3. A match occurs when the best bid price >= best ask price
  4. Partial fills are supported β€” remaining quantity stays in the book

License

MIT License

About

A high-performance order matching engine written in Go

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages