ker

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 16 Imported by: 0

README

Order Matching Engine

Go

A high-performance order matching engine for financial exchanges, built with Go 1.21 as a study project.

Features

  • Order Matching: SkipList-based matching for efficient price-level ordering
  • Order Types: GTC, IOC, FOK, and POC (Post-Only/Pending-Or-Cancelled)
  • Concurrency: Simultaneous order processing with goroutines and channels
  • Order Cancellation: Full support for order revocation
  • Snapshots: Order book state capture for recovery and analysis
  • WAL: Write-Ahead Logging for data integrity and fast recovery
  • Redo Processing: Error correction through redo log replay

Quick Start

// Create orders (negative Amount represents ask orders)
bidOrder := &types.KernelOrder{
    Amount: 100,
    Price:  200,
    Left:   100,
}
askOrder := &types.KernelOrder{
    Amount: -100,
    Price:  201,
    Left:   -100,
}

// Initialize acceptor
acceptor := initAcceptor(1, "test")
go acceptor.orderAcceptor()
acceptor.kernel.startDummyMatchedInfoChan()

// Submit orders
go func() {
    acceptor.newOrderChan <- bidOrder
    acceptor.newOrderChan <- askOrder
}()

See kernel_test.go for complete usage examples.

Architecture

Core Components
Component Description
kernel Core matching engine with ask/bid SkipLists
priceBucket Price level container using container/list
matchedInfo Match result with maker orders and taker order
scheduler Order acceptor and scheduler
Data Structures

SkipList: Maintains order books sorted by price for efficient matching

priceBucket:

  • l: List of orders at this price level
  • Left: Total remaining amount

KernelOrder: 72-byte order struct with fixed-size fields for binary serialization

Channels
  • matchedInfoChan: Matched order notifications
  • errorInfoChan: Error reporting
  • newOrderChan: Incoming orders
  • orderReceivedChan: Order receipt confirmations

Testing

go test -v ./...
GOMAXPROCS=1 go test -bench=. -run=none -benchtime=1s -benchmem
./cover.sh  # HTML coverage report

TODO

  • Monitoring integration
  • Kernel data visualization

License

MIT License

Documentation

Index

Constants

View Source
const (
	DISABLED redoKernelStatus = iota
	WAITTING_START
	STARTED
	WAITTING_STOP
	STOPPED
)
View Source
const (
	// Suitable for math.Floor(math.Pow(math.E, 18)) == 65659969 elements in list
	DefaultMaxLevel    int     = 18
	DefaultProbability float64 = 1 / math.E
)
View Source
const (
	REDO_KERNEL = 1
)

Variables

This section is empty.

Functions

func SetSaveOrderLog

func SetSaveOrderLog(v bool)

SetSaveOrderLog controls whether orders are written to the WAL log file.

Types

type Element

type Element struct {
	// contains filtered or unexported fields
}

func (*Element) Key

func (e *Element) Key() float64

Key allows retrieval of the key for a given Element

func (*Element) Next

func (e *Element) Next() *Element

Next returns the following Element or nil if we're at the end of the list. Only operates on the bottom level of the skip list (a fully linked list).

func (*Element) Value

func (e *Element) Value() interface{}

Value allows retrieval of the value for a given Element

type KernelErr

type KernelErr error

type MatchResult

type MatchResult struct {
	TakerOrder     types.KernelOrder
	MakerOrders    []types.KernelOrder
	MatchedSizeMap map[uint64]int64
}

MatchResult holds the result of a matching event.

type MatchingEngine

type MatchingEngine struct {
	// contains filtered or unexported fields
}

MatchingEngine is the exported wrapper around the internal matching kernel.

func NewMatchingEngine

func NewMatchingEngine(serverID uint64, desc string) *MatchingEngine

NewMatchingEngine creates a new matching engine instance.

func (*MatchingEngine) AskLength

func (e *MatchingEngine) AskLength() int

AskLength returns the number of ask price levels.

func (*MatchingEngine) BestAsk

func (e *MatchingEngine) BestAsk() int64

BestAsk returns the current best (lowest) ask price.

func (*MatchingEngine) BestBid

func (e *MatchingEngine) BestBid() int64

BestBid returns the current best (highest) bid price.

func (*MatchingEngine) BidLength

func (e *MatchingEngine) BidLength() int

BidLength returns the number of bid price levels.

func (*MatchingEngine) MatchedInfoChan

func (e *MatchingEngine) MatchedInfoChan() <-chan MatchResult

MatchedInfoChan returns a read-only channel of match results.

func (*MatchingEngine) OrderBook

func (e *MatchingEngine) OrderBook() *OrderBookSnapshot

OrderBook returns a snapshot of the current order book.

func (*MatchingEngine) Start

func (e *MatchingEngine) Start()

Start begins order processing. Must be called before submitting orders.

func (*MatchingEngine) Stop

func (e *MatchingEngine) Stop()

Stop gracefully shuts down the matching engine.

func (*MatchingEngine) SubmitOrder

func (e *MatchingEngine) SubmitOrder(order *types.KernelOrder)

SubmitOrder sends an order into the matching engine.

type OrderBookSnapshot

type OrderBookSnapshot struct {
	Asks []PriceLevel `json:"asks"`
	Bids []PriceLevel `json:"bids"`
}

OrderBookSnapshot is a snapshot of the current order book.

type PriceLevel

type PriceLevel struct {
	Price int64 `json:"price"`
	Size  int64 `json:"size"`
}

PriceLevel represents a single price level in the order book.

type SkipList

type SkipList struct {
	Length int
	// contains filtered or unexported fields
}

func NewSkipList

func NewSkipList() *SkipList

NewSkipList creates a new skip list with default parameters. Returns a pointer to the new list.

func NewWithMaxLevel

func NewWithMaxLevel(maxLevel int) *SkipList

NewWithMaxLevel creates a new skip list with MaxLevel set to the provided number. maxLevel has to be int(math.Ceil(math.Log(N))) for DefaultProbability (where N is an upper bound on the number of elements in a skip list). See http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.524 Returns a pointer to the new list.

func (*SkipList) Front

func (list *SkipList) Front() *Element

Front returns the head node of the list.

func (*SkipList) Get

func (list *SkipList) Get(key float64) *Element

Get finds an element by key. It returns element pointer if found, nil if not found. Locking is optimistic and happens only after searching with a fast check for deletion after locking.

func (*SkipList) Remove

func (list *SkipList) Remove(key float64) *Element

Remove deletes an element from the list. Returns removed element pointer if found, nil if not found. This method is NOT thread-safe and should be called only when the list is not being accessed by other goroutines.

func (*SkipList) Set

func (list *SkipList) Set(key float64, value interface{}) *Element

Set inserts a value in the list with the specified key, ordered by the key. If the key exists, it updates the value in the existing node. Returns a pointer to the new element. Locking is optimistic and happens only after searching.

func (*SkipList) SetProbability

func (list *SkipList) SetProbability(newProbability float64)

SetProbability changes the current P value of the list. It doesn't alter any existing data, only changes how future insert heights are calculated.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL