match

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: GPL-3.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Matching Engine SDK

A high-performance, in-memory matching engine SDK written in Go. Designed for crypto exchanges, trading simulations, and financial systems requiring precise and fast order execution.

🚀 Features

  • High Performance: Pure in-memory matching using efficient SkipList data structures ($O(\log N)$) and Disruptor pattern (RingBuffer) for microsecond latency.
  • Deterministic Execution (RSM Ready): 100% free of time.Now() in engine logic. All state transitions and event timestamps strictly derive from authoritative external logical clocks (e.g. sequencer timestamps), guaranteeing bit-for-bit deterministic replay across nodes in Replicated State Machines (RSM) and event sourcing architectures.
  • Dual Integration Modes:
    • Synchronous OrderBook: Direct in-memory matching without background workers, ideal for embedding into single-goroutine state machines, Raft loops, or partitioned workers.
    • Asynchronous MatchingEngine: Complete multi-market actor with Disruptor MPSC ring buffer for high-concurrency standalone services.
  • Market Data Depth Feed (DepthDeltaBuilder / AggregatedBook): The book produces one DepthDelta per SDK call that moves visible depth, with the new absolute size of each changed level. A downstream AggregatedBook applies it with ApplyDelta, which checks the version, skips resends, and reloads a snapshot on a gap (OnRebuild). Thread-safe depth queries (GetDepth).
  • Single Thread Actor: Adopts a Lock-Free architecture where a single pinned goroutine processes all state mutations. This eliminates context switching and mutex contention, maximizing CPU cache locality.
  • Concurrency Safe: All state mutations are serialized through the RingBuffer or single-actor loops, eliminating race conditions without mutex lock contention.
  • Low Allocation Hot Paths: Uses udecimal (uint64-based), intrusive lists, and object pooling to achieve 0 allocs/op on core matching paths.
  • Multi-Market Support: Manages multiple trading pairs (e.g., BTC-USDT, ETH-USDT) within a single MatchingEngine instance.
  • Comprehensive Order Types:
    • Limit, Market (Size or QuoteSize), IOC, FOK, Post Only
    • Iceberg Orders: Support for hidden size with automatic replenishment.
  • Event Sourcing: Generates detailed OrderBookLog events allowing for deterministic replay and state reconstruction.

📦 Installation

go get github.com/0x5487/matching-engine

🛠 Usage

1. Synchronous OrderBook (Direct State Machine / Event Sourcing)

For Replicated State Machines (RSM), event-sourced loops, or partitioned single-goroutine workers, use match.OrderBook directly. Matching executes synchronously on the caller's goroutine with zero queue hops, returning the resulting *LogBatch immediately.

package main

import (
	"fmt"

	match "github.com/0x5487/matching-engine"
	"github.com/0x5487/matching-engine/protocol"
	"github.com/quagmt/udecimal"
)

func main() {
	// 1. Initialize OrderBook with optional configurations
	book := match.NewOrderBook(
		"BTC-USDT",
		match.WithEngineID("engine-1"),
	)

	// 2. Place a Sell Order synchronously
	// Note: Timestamp must come from your sequencer (e.g. NATS JetStream meta.Timestamp)
	sellBatch, err := book.PlaceOrder(&protocol.PlaceOrderRequest{
		STPMode: protocol.STPModeNone,
		BaseCommand: protocol.BaseCommand{
			CommandID: "cmd-sell-1",
			MarketID:  "BTC-USDT",
			UserID:    1001,
			Timestamp: 1774000000000000000, // Authoritative logical timestamp
		},
		OrderID:   "sell-1",
		OrderType: protocol.OrderTypeLimit,
		Side:      protocol.SideSell,
		Price:     udecimal.MustFromInt64(50000, 0),
		Size:      udecimal.MustFromInt64(1, 0),
		StepSize:  udecimal.MustFromInt64(1, 8),
	})
	if err != nil {
		panic(err)
	}
	// sellBatch is the book's own batch: valid until the next call on this book.

	// 3. Place a Matching Buy Order synchronously (matches immediately)
	buyBatch, err := book.PlaceOrder(&protocol.PlaceOrderRequest{
		STPMode: protocol.STPModeNone,
		BaseCommand: protocol.BaseCommand{
			CommandID: "cmd-buy-1",
			MarketID:  "BTC-USDT",
			UserID:    1002,
			Timestamp: 1774000000000001000,
		},
		OrderID:   "buy-1",
		OrderType: protocol.OrderTypeLimit,
		Side:      protocol.SideBuy,
		Price:     udecimal.MustFromInt64(50000, 0),
		Size:      udecimal.MustFromInt64(1, 0),
		StepSize:  udecimal.MustFromInt64(1, 8),
	})
	if err != nil {
		panic(err)
	}

	// 4. Immediately inspect match results (e.g. for atomic balance settlement)
	for _, log := range buyBatch.Logs {
		if log.Type == protocol.LogTypeMatch {
			fmt.Printf("[MATCH] TradeID: %d, Price: %s, Size: %s, Maker: %s, Taker: %s\n",
				log.TradeID, log.Price, log.MatchSize, log.MakerOrder.ID, log.OrderID)
		}
	}

	// 5. Query Depth or Take In-Memory Snapshot
	depth := book.GetDepth(10)
	if len(depth.Asks) > 0 {
		fmt.Printf("Best Ask: %s\n", depth.Asks[0].Price)
	}

	snapshot := book.Snapshot()
	restoredBook := match.NewOrderBook("BTC-USDT")
	if err := restoredBook.Restore(snapshot); err != nil {
		panic(err)
	}
}
2. Asynchronous Matching Engine (Disruptor / Actor Pattern)
package main

import (
	"context"
	"fmt"
	"time"

	match "github.com/0x5487/matching-engine"
	"github.com/0x5487/matching-engine/protocol"
	"github.com/quagmt/udecimal"
)

func main() {
	ctx := context.Background()

	// 1. Create a PublishLog handler (implement your own for non-memory usage)
	publish := match.NewMemoryPublishLog()

	// 2. Initialize the Matching Engine
	engine := match.NewMatchingEngine("engine-1", publish)

	// 3. Start the Engine (Actor Loop)
	// This must be run in a separate goroutine
	go func() {
		if err := engine.Run(); err != nil {
			panic(err)
		}
	}()

	// 4. Markets arrive with a snapshot. There is no create-market command: the
	// market list belongs to whoever serves the API, and this library's job is
	// matching. To start from scratch rather than from a snapshot, drive
	// NewOrderBook directly and register it.

	// 5. Place a Sell Limit Order
	sellReq := &protocol.PlaceOrderRequest{
		STPMode: protocol.STPModeNone,
		BaseCommand: protocol.BaseCommand{
			CommandID: "sell-1-cmd",
			MarketID:  "BTC-USDT",
			UserID:    1001,
			Timestamp: time.Now().UnixNano(),
		},
		OrderID:   "sell-1",
		OrderType: protocol.OrderTypeLimit,
		Side:      protocol.SideSell,
		Price:     udecimal.MustFromInt64(50000, 0), // 50000
		Size:      udecimal.MustFromInt64(1, 0),     // 1.0
		StepSize:  udecimal.MustFromInt64(1, 8),     // 0.00000001
	}
	if err := engine.PlaceOrderAsync(ctx, sellReq); err != nil {
		fmt.Printf("Error placing sell order: %v\n", err)
	}

	// 6. Place a Buy Limit Order (Matches immediately)
	buyReq := &protocol.PlaceOrderRequest{
		STPMode: protocol.STPModeNone,
		BaseCommand: protocol.BaseCommand{
			CommandID: "buy-1-cmd",
			MarketID:  "BTC-USDT",
			UserID:    1002,
			Timestamp: time.Now().UnixNano(),
		},
		OrderID:   "buy-1",
		OrderType: protocol.OrderTypeLimit,
		Side:      protocol.SideBuy,
		Price:     udecimal.MustFromInt64(50000, 0), // 50000
		Size:      udecimal.MustFromInt64(1, 0),     // 1.0
		StepSize:  udecimal.MustFromInt64(1, 8),     // 0.00000001
	}
	if err := engine.PlaceOrderAsync(ctx, buyReq); err != nil {
		fmt.Printf("Error placing buy order: %v\n", err)
	}

	// Allow some time for async processing
	time.Sleep(100 * time.Millisecond)

	// 7. Check Logs
	fmt.Printf("Total events: %d\n", publish.Count())
	logs := publish.Logs()
	for _, log := range logs {
		switch log.Type {
		case protocol.LogTypeMatch:
			fmt.Printf("[MATCH] TradeID: %d, Price: %s, Size: %s\n",
				log.TradeID, log.Price, log.MatchSize)
		case protocol.LogTypeOpen:
			fmt.Printf("[OPEN] OrderID: %s, Price: %s\n", log.OrderID, log.Price)
		}
	}
}
3. Depth Feed: DepthDeltaBuilder and AggregatedBook (Downstream Market Data)

Downstream read services (Market Data Services, WebSocket gateways, Redis snapshot updaters) keep a live, aggregated view of the depth. The book itself produces the changes; the view only applies them.

Key capabilities:

  • One version per call: OrderBook.SeqID() is the depth version. One SDK call (PlaceOrder, CancelOrder, AmendOrder) that moves visible depth advances it by exactly one, and every depth log of that call carries the new value. A refusal, an admin command, a no-op amend or a shrink inside the hidden size does not advance it.
  • Producer (DepthDeltaBuilder): Add or AddBatch the logs of a call, then Flush(book, &delta) reads the touched levels from the book and fills a protocol.DepthDelta (Seq, Asks ascending, Bids descending; a size of zero means the level is gone), then Reset. Which levels a log moves comes from CalculateDepthChange, the single depth rule. Flush must run before the next call changes the book, because it reads sizes as they are then. Several calls may be added before one Flush; the delta then holds each level once at its final size and carries the last version.
  • Follower (AggregatedBook.ApplyDelta): a delta with Seq one past the follower's version sets each level and advances the version. A resend (Seq at or below the version) is skipped. A gap calls OnRebuild for a snapshot; the snapshot is applied only if it reaches the delta, and otherwise ErrSequenceGap is returned with the book unchanged. A malformed delta is refused with ErrInvalidDepthDelta before anything changes. A snapshot is a protocol.DepthDelta that lists every level, with Seq the version it was taken at; ApplySnapshot checks it as a whole, so a negative size or a price written twice on one side leaves the book as it was.
  • Prices are compared by value: 100 and 100.00 are one level, on the book and in the delta. The book keys its price maps by a canonical form, so the second order written at the same price joins the first instead of resting on a level of its own.
  • Queries on the book: LevelSize(side, price) is the visible size at one price, BestPrice(side) the best price of a side, Remaining(orderID) the total base size an order still has on the book, visible plus hidden, OrderCount() how many orders rest on the book, DepthCount(side) how many price levels rest on one side, and Order(orderID) a copy of the order as the book holds it: its user, side, price, sizes, its routing (OmsShard, MakerFeeRate, TakerFeeRate, BaseAsset, QuoteAsset) and FilledSize, the base it has traded over its life. The second result of each is false for an order that is gone. All are read from the book, so a caller holds no second copy of depth, of an order's remaining size or of its routing. A cancel answers the same quantities as Order would, from its own single lookup, in CancelResult; it does not need a query first.
  • Routing travels with the order: the caller of PlaceOrder sets the routing fields of PlaceOrderRequest, and the book keeps them on the order and never reads them. A Match log names its maker once, in MakerOrder, as the trade left it: the maker's ID and user, its shard, fee rate and assets, so a consumer that settles a fill finds them on the log itself, including for a maker that the same call consumes whole.
  • Thread-Safe Queries: AggregatedBook is protected by an internal sync.RWMutex; GetDepth and Depth may run beside ApplyDelta, which has one writer.
package main

import (
	"fmt"

	"github.com/quagmt/udecimal"

	match "github.com/0x5487/matching-engine"
	"github.com/0x5487/matching-engine/protocol"
)

func main() {
	book := match.NewOrderBook("BTC-USDT")
	feed := match.NewDepthDeltaBuilder()
	view := match.NewAggregatedBook()

	// 1. Configure OnRebuild for a gap: a snapshot at the version the follower missed.
	view.OnRebuild = func() (*protocol.DepthDelta, error) {
		return &protocol.DepthDelta{
			Seq:  100,
			Asks: []protocol.DepthLevel{{Price: udecimal.MustParse("50100"), Size: udecimal.MustParse("2.5")}},
			Bids: []protocol.DepthLevel{{Price: udecimal.MustParse("50000"), Size: udecimal.MustParse("1.2")}},
		}, nil
	}

	// 2. After each call on the book, turn its logs into a delta and apply it.
	batch, err := book.PlaceOrder(&protocol.PlaceOrderRequest{ /* ... */ })
	if err != nil {
		panic(err)
	}
	feed.AddBatch(batch.Logs)

	var delta protocol.DepthDelta
	if feed.Flush(book, &delta) {
		if err := view.ApplyDelta(&delta); err != nil {
			panic(err)
		}
	}
	feed.Reset()

	// 3. Query top N depth levels (e.g. to write to Redis or push via WebSocket)
	depth := view.GetDepth(20)
	fmt.Printf("UpdateID: %d\n", depth.UpdateID)
	if len(depth.Asks) > 0 {
		fmt.Printf("Best Ask: %s (%s)\n", depth.Asks[0].Price, depth.Asks[0].Size)
	}
	if len(depth.Bids) > 0 {
		fmt.Printf("Best Bid: %s (%s)\n", depth.Bids[0].Price, depth.Bids[0].Size)
	}
}
Wire Transport (MQ / Cross-Process)

MarshalRequest and UnmarshalRequest serialize typed requests to and from a compact binary format for use in message queues and cross-process communication.

// Serialize a request for MQ publishing.
// MarshalRequest derives the wire CommandType from the concrete Go type,
// so cross-process dispatch is always correct.
req := &protocol.PlaceOrderRequest{
    STPMode: protocol.STPModeNone,
    BaseCommand: protocol.BaseCommand{
        CommandID: "sell-1-cmd",
        MarketID:  "BTC-USDT",
        UserID:    1001,
        Timestamp: time.Now().UnixNano(),
    },
    OrderID:   "sell-1",
    OrderType: protocol.OrderTypeLimit,
    Side:      protocol.SideSell,
    Price:     udecimal.MustFromInt64(50000, 0),
    Size:      udecimal.MustFromInt64(1, 0),
}

data, err := protocol.MarshalRequest(req)
// ... publish data to MQ ...

// On the consumer side:
decoded, err := protocol.UnmarshalRequest(data)
// decoded is typed as any; use GetRequestBase or a type switch to dispatch.
Request Semantics
  • Strict Authoritative Timestamp: Every state-changing request (PlaceOrderRequest, CancelOrderRequest, AmendOrderRequest, management commands) must carry an upstream-assigned non-zero logical Timestamp (Unix nanoseconds, e.g. from sequencer metadata). Requests with Timestamp <= 0 are strictly rejected with protocol.RejectReasonInvalidPayload. The engine never calls time.Now() internally.
  • Synchronous vs. Asynchronous:
    • Synchronous Mode (book.PlaceOrder, book.CancelOrder, book.AmendOrder): Immediately performs in-memory matching on the caller's goroutine. PlaceOrder and AmendOrder return (*LogBatch, error). CancelOrder returns (CancelResult, error): its Batch is the call's batch, and its other fields are the order as the call's single lookup found it just before the cancel, its owner (UserID), its filled base (FilledSize) and its total remaining base, visible plus hidden (Remaining). A caller that needs those quantities for its answer reads them here instead of calling Order(orderID) first, so a cancel is one lookup and no copy of the order. Found is false when the book held no such order, and the batch then holds the reject. A found order whose owner differs from the request's user is refused as RejectReasonOrderNotFound with Found still true, so a caller can tell a wrong owner from an order that is gone; a payload refused before the cancel reports the order it found with the refusal's own reason. The batch belongs to the book, so there is nothing to release: the batch and its logs stay valid until the next call on the same book, which reclaims them when it starts. Consume them before that call, and do not retain any *OrderBookLog or the Logs slice across it. Different books have different batches, so calls on several books may interleave.
    • Asynchronous Mode (engine.PlaceOrderAsync, etc.): Enqueues work into the Disruptor MPSC ring buffer. A returned error means enqueue failure, not business rejection.
  • Every request must carry an upstream-assigned non-empty CommandID. Engine helpers reject empty command IDs before enqueue.
  • Business-level failures are emitted as OrderBookLog entries with Type == protocol.LogTypeReject.
  • Self-trade prevention mode is required: every PlaceOrderRequest names an STPMode. Zero is refused with invalid_payload (the book does not guess), and so is CancelBoth with a FOK order. See Self-Trade Prevention.
  • Canonical price levels: 100, 100.0 and 100.00 are one level. The book keys each price by its canonical value (the 128-bit coefficient with trailing zeros removed) and computes that key once when the order enters, at placement or amend. A price whose coefficient needs more than 128 bits has no such key; PlaceOrder and AmendOrder refuse it with invalid_payload before the book or the depth version moves. Keep prices within that range and write them without a huge run of trailing zeros. A snapshot containing a price the book now refuses is not restorable; discard it and rebuild from the command log.
  • Requests sent to a missing market generate a reject event with RejectReasonMarketNotFound.
  • Unknown query types will return ErrUnknownQuery through the Future.Wait() call.
  • The Query() method uses a *protocol.Query request and returns ErrNotFound immediately when the market does not exist.
Querying Market State

Query the engine for read-only state such as order book depth or statistics:

// 1. Query Market Statistics
statsQuery := &protocol.Query{
	Type:     protocol.QueryGetStats,
	MarketID: "BTC-USDT",
}
future, err := engine.Query(ctx, statsQuery)
res, err := future.Wait(ctx)
if err == nil {
	stats := res.(*protocol.GetStatsResponse)
	fmt.Printf("Bids: %d, Asks: %d\n", stats.BidOrderCount, stats.AskOrderCount)
}

// 2. Query Order Book Depth
depthQuery := &protocol.Query{
	Type:     protocol.QueryGetDepth,
	MarketID: "BTC-USDT",
	Payload:  &protocol.GetDepthRequest{Limit: 10},
}
future, err = engine.Query(ctx, depthQuery)
res, err = future.Wait(ctx)
if err == nil {
	depth := res.(*protocol.GetDepthResponse)
	if len(depth.Bids) > 0 {
		fmt.Printf("Top Bid: %s\n", depth.Bids[0].Price)
	}
}
Market Lifecycle

There is none, by design. Market creation, suspension and configuration are not this library's business: an order book matched orders that were already routed to it, and the set of tradeable markets is decided upstream. The top-level MatchingEngine therefore has one way to obtain a book - restoring it from a snapshot - and the synchronous OrderBook API is the entry point for callers that manage books themselves.

Supported Order Types
Type Description
Limit Buy/sell at a specific price or better
Market Execute immediately at best available price. Sized by exactly one of Size (base quantity) or QuoteSize (quote amount); sending both, or neither, is refused as invalid_payload. StepSize is required with either — see Step Size.
IOC Fill immediately, cancel unfilled portion.
FOK Fill entirely immediately or cancel completely.
PostOnly Add to book as maker only, reject if would match immediately.

Only a market order reads QuoteSize. A Limit, IOC, FOK or PostOnly order is sized by Size alone, and a QuoteSize on it is ignored.

A fill never crosses its order's price rule. The maker always fills at exactly its own resting price. A limit taker (limit GTC, IOC or FOK) fills at that price only when it is no worse than its limit: a buy at or below it, a sell at or above it. A market order's Price, when non-zero, is its protection price and bounds the fill the same way. An amended order's new price is the one that counts. The tests pin this for every order type, including post-only and iceberg makers, market orders by size and by quote, several levels, partial fills and an amended price.

Self-Trade Prevention

An order carries an STPMode and an STPGroup. When a taker would trade with a resting order of the same UserID, or of the same non-zero STPGroup, the taker's mode decides; the resting order's own mode is never read for that.

STPMode Value What happens to the resting order What happens to the taker
STPModeCancelMaker 1 Cancelled (hidden iceberg size included, no reload) Walks on to the next order
STPModeCancelTaker 2 Stays Its remainder ends with a Reject, self_trade_prevented
STPModeCancelBoth 3 Cancelled Its remainder ends with a Reject, self_trade_prevented
STPModeNone 4 Stays Trades as if there were no prevention
zero, or any value outside 1-4 0, 5, ... not a mode The whole order is refused, invalid_payload, and the book does not move
  • Group zero is no group. Two orders that both have STPGroup == 0 are not the same group; only the same UserID counts then.
  • Cancelled resting order. The book writes a Cancel log with CancelReason == stp. Its OrderID, UserID, Side, Price and Type are the cancelled order's; Remaining is its whole total, visible plus hidden; VisibleRemoved is the visible part, the only part that was depth; MakerOrder is a copy with the order's OmsShard and FilledSize. A user's own cancel has CancelReason == user and no MakerOrder.
  • Ended taker. A Reject log with RejectReason == self_trade_prevented, carrying Side, Price, OrderType and the unfilled Remaining (or QuoteRemaining for a quote-sized market order). What the taker traded before it met the order stands. With cancel_both the Cancel log comes first.
  • Depth version. One call moves the version by one, as everywhere: a cancelled order, the trades and the rest of the taker share it. A cancel_taker that only ends the taker moves no depth.
  • Where it is checked. After the price bound (a market order's protection price, an IOC or limit price), so an order beyond the bound is never cancelled. Post-only is unchanged: if it would trade it is refused whole, whoever the other side is, and nothing is cancelled.
  • FOK. The price-level totals are checked first, with the same reasons as ever. With cancel_maker or cancel_taker the book then walks the orders and checks what the taker can really fill: cancel_maker leaves its own orders out; cancel_taker can only fill what lies before its first own order, and an iceberg at that order's price counts its visible size alone (its reload queues behind). A taker that cannot be filled whole is refused insufficient_size and the book is untouched.
  • Amend. An amend that loses priority matches again with the STPMode and STPGroup the order was placed with.
  • Snapshots. Both fields are saved with a resting order. Restore refuses a resting order whose STPMode is zero.
  • Wire. MarshalRequest writes STPGroup (8 bytes) and STPMode (1 byte) right after OmsShard.
Step Size

StepSize is the unit of account for the base asset. A base balance has to be a whole number of steps or it cannot be reconciled against a ledger, which makes it more than an order-size rule: it is what the balance is denominated in.

It travels on PlaceOrderRequest rather than living on the book. That means a replay cannot disagree with itself about which unit was in force, and no producer can pick a unit the market does not use — the caller that fills it in is the one that knows the market's rules.

It is required whenever a quantity has to be checked: Size or VisibleSize on a new order, QuoteSize, and NewSize on an amend. A quantity must be a whole number of steps, so an order that names one with a zero or negative StepSize has nothing to be measured against and is refused as invalid_payload, with the book unchanged. A quote-sized order additionally divides the quote by each level's price and floors the result to the step. A price-only amend (NewSize zero) checks no quantity and needs no step.

// Buy as much as 100 USDT buys. The step size floors each level's conversion so
// the resulting balance is a whole number of steps; anything left over stays as
// quote and is reported back to the caller through the reject log.
req := &protocol.PlaceOrderRequest{
	STPMode: protocol.STPModeNone,
	OrderType: protocol.OrderTypeMarket,
	Side:      protocol.SideBuy,
	QuoteSize: udecimal.MustFromInt64(100, 0), // 100 USDT
	StepSize:  udecimal.MustFromInt64(1, 4),   // 0.0001
}

The floor happens before the minimum with the resting order, not after. That ordering is what keeps an offer placed under an older, finer step reachable: flooring after sends 0.0003 to zero at a 0.001 step, rejects an order the book could have filled, and lets one holder's dust refuse every order behind it.

Event Handling

Implement Publisher interface to handle order book events.

Publish must not retain anything it is given. The logs stay valid until the next call on the book that produced them (or the engine's next event), and that call reclaims them: the logs are zeroed and their storage is reused for the next call's logs. A log that is read after that point reads recycled memory — usually zeros. Publish receives only []*OrderBookLog, not the *LogBatch, so an implementation cannot reclaim the logs itself and never needs to.

If the logs are needed beyond the call — for a channel, a goroutine, or a queue — copy them before returning:

type MyHandler struct {
	mu   sync.Mutex
	kept []match.OrderBookLog
}

func (h *MyHandler) Publish(logs []*match.OrderBookLog) {
	for _, log := range logs {
		copyLog := *log // copy before returning; the original is reused on the book's next call
		h.mu.Lock()
		h.kept = append(h.kept, copyLog)
		h.mu.Unlock()
	}
}

A user event's SeqID is 0, since a user event has no depth version. The book keeps no upstream command sequence: a caller that needs its message queue offset keeps it itself and saves it with its own state.

Log quantity fields

Each quantity field of OrderBookLog has one meaning. A log leaves the fields that do not apply at zero, so a field that is non-zero says what its log did:

Field Meaning Set by
MatchSize the base quantity traded; the visible size the maker gives up (a match never consumes an iceberg's hidden part) Match
Remaining the order's total remaining base size, visible plus hidden: the total after an open rests, the new total of an amend, the total a cancel removes, the base quantity a reject did not get Open, Amend, Cancel, Reject (quantity-sized; never set on a quote-sized reject)
OldRemaining the total before the amend Amend
VisibleAdded the visible size an open puts on the book (the visible part of Remaining) Open
VisibleRemoved the visible size a cancel or an amend takes off the book, at OldPrice Cancel, Amend
QuoteRemaining the quote a quote-sized market order did not spend Reject (quote-sized; never set on a quantity-sized reject)
MakerOrder the maker of the trade as it is after the trade and before any replenish it triggers: its ID and UserID, its routing, its Size (visible) and HiddenSize left, and its FilledSize. It is the only place a match names its maker. A cancel with CancelReason stp fills it with the cancelled order as it was Match, Cancel (stp)
CancelReason why a cancel removed its order: user (the owner asked) or stp (the book prevented a self trade). Empty on every other log Cancel

Price, OldPrice, Amount and the identifiers keep their usual meaning. Open and Cancel do not use Amount; Amount is the quote of a match only.

A publisher that only inspects the logs in place, as below, is also correct:

func (h *MyHandler) Publish(logs []*match.OrderBookLog) {
	for _, log := range logs {
		if log.Type == protocol.LogTypeUser {
			fmt.Printf("User Event: %s, Data: %s\n", log.EventType, string(log.Data))
		} else if log.Type == protocol.LogTypeAdmin {
			fmt.Printf("Admin Event: %s | Market: %s\n", log.EventType, log.MarketID)
		} else {
			fmt.Printf("Event: %s | OrderID: %s\n", log.Type, log.OrderID)
		}
	}
}
Generic User Events (Extension Protocol)

Inject custom events into the matching engine's log stream.

// Example: Sending an End-Of-Block signal
userEventReq := &protocol.UserEventRequest{
	BaseCommand: protocol.BaseCommand{
		CommandID: "block-100-event",
		UserID:    999,
		Timestamp: time.Now().UnixNano(),
	},
	EventType: "EndOfBlock",
	Key:       "block-100",
	Data:      []byte("0x123abc..."),
}
err := engine.SendUserEvent(ctx, userEventReq)
Snapshot and Restore
1. Synchronous OrderBook (In-Memory Struct)

For custom storage layers, Raft state machines, or embedding into external snapshots:

// 1. Capture in-memory snapshot
snapshot := book.Snapshot()

// 2. Restore state into a new OrderBook instance. Restore checks every order
// first: a snapshot it cannot hold (a price beyond 128 coefficient bits) returns
// an error wrapping ErrInvalidParam and leaves the book as it was.
restoredBook := match.NewOrderBook("BTC-USDT")
if err := restoredBook.Restore(snapshot); err != nil {
	return err
}
2. MatchingEngine (Disk-based Multi-Market Snapshot)

Persist full multi-market engine state to disk and restore after restarts:

// Take disk snapshot. The logical timestamp is required and is stored as given;
// a call without a positive one returns an error and writes nothing.
meta, err := engine.TakeSnapshot(ctx, "./snapshot", seqTimestamp)
if err != nil {
	panic(err)
}

// Restore entire engine from disk snapshot
restored := match.NewMatchingEngine("engine-1-restored", publish)
meta, err = restored.RestoreFromSnapshot("./snapshot")
if err != nil {
	panic(err)
}
_ = meta // meta.Timestamp is the timestamp the snapshot was taken with

Benchmark

Run engine benchmarks:

make bench

Run aggregated book read-replica benchmarks:

make bench-aggrbook

Please refer to docs for detailed benchmarks.

Documentation

Index

Constants

View Source
const (
	// EngineVersion is the current version of the matching engine.
	EngineVersion = "v0.9.0"

	// SnapshotSchemaVersion is the current version of the snapshot schema
	// Increment this when the snapshot format changes in a backward-incompatible way.
	SnapshotSchemaVersion = 1
)

Variables

View Source
var (
	// ErrInsufficientLiquidity is returned when there is not enough depth to fill a Market/IOC/FOK order.
	ErrInsufficientLiquidity = errors.New("there is not enough depth to fill the order")
	// ErrInvalidParam is returned when a parameter is invalid.
	ErrInvalidParam = errors.New("the param is invalid")
	// ErrInternal is returned when an internal server error occurs.
	ErrInternal = errors.New("internal server error")
	// ErrTimeout is returned when an operation times out.
	ErrTimeout = errors.New("timeout")
	// ErrShutdown is returned when the engine is shutting down.
	ErrShutdown = errors.New("order book is shutting down")
	// ErrNotFound is returned when a resource is not found.
	ErrNotFound = errors.New("not found")
	// ErrInvalidPrice is returned when a price is invalid.
	ErrInvalidPrice = errors.New("invalid price")
	// ErrInvalidSize is returned when a size is invalid.
	ErrInvalidSize = errors.New("invalid size")
	// ErrOrderBookClosed is returned when the order book is closed.
	ErrOrderBookClosed = errors.New("order book is closed")
	// ErrUnknownCommand is returned when the command type is unknown.
	ErrUnknownCommand = errors.New("unknown command")
	// ErrUnknownQuery is returned when the query type is unknown.
	ErrUnknownQuery = errors.New("unknown query")
	// ErrSequenceGap is returned when a sequence gap is detected in order book logs.
	ErrSequenceGap = errors.New("sequence gap detected")
	// ErrInvalidDepthDelta is returned when a depth delta is malformed: nil, Seq zero,
	// a negative size, or a side whose levels are not strictly ordered by price. The
	// book is left unchanged.
	ErrInvalidDepthDelta = errors.New("invalid depth delta")
	// ErrNilSnapshot is returned when attempting to apply a nil snapshot.
	ErrNilSnapshot = errors.New("snapshot is nil")
	// ErrOnRebuildNotSet is returned when rebuild is triggered but OnRebuild callback is not set.
	ErrOnRebuildNotSet = errors.New("OnRebuild callback not set")
)
View Source
var ErrDisruptorTimeout = errors.New("disruptor: shutdown timeout")

ErrDisruptorTimeout is returned when shutdown times out.

Functions

This section is empty.

Types

type AggregatedBook added in v0.7.0

type AggregatedBook struct {

	// OnRebuild is called when a rebuild is needed (e.g., sequence gap detected).
	// The callback should return a snapshot from which the book will be rebuilt.
	// This must be set before calling Rebuild(), or before ApplyDelta meets a gap.
	OnRebuild RebuildFunc
	// contains filtered or unexported fields
}

AggregatedBook maintains a simplified view of the order book, tracking only price levels and their aggregated sizes (depth). It is designed for downstream services that follow an OrderBook through the DepthDelta feed produced by DepthDeltaBuilder and applied with ApplyDelta.

One lock guards the version and the levels together, so a reader never sees a version that the levels do not have. The levels are treemaps compared by value, so 100 and 100.00 are one level.

func NewAggregatedBook added in v0.7.0

func NewAggregatedBook() *AggregatedBook

NewAggregatedBook creates a new AggregatedBook instance with empty ask and bid sides.

func (*AggregatedBook) ApplyDelta added in v0.9.0

func (ab *AggregatedBook) ApplyDelta(d *protocol.DepthDelta) error

ApplyDelta applies a DepthDelta produced by an OrderBook. The delta's Seq is compared with the version the book has reached, cur:

  • Seq == cur+1: each level is set to its size, zero removes the level, and the version becomes Seq.
  • Seq <= cur: the delta was applied already. Nothing changes and nil is returned.
  • Seq > cur+1: a version was missed. Without OnRebuild, ErrSequenceGap is returned. With it, the snapshot is fetched and applied only if it reaches Seq-1 or further, and the delta is then applied or skipped as above. A snapshot that still leaves a gap is not applied, and ErrSequenceGap is returned with the book unchanged.

A malformed delta (nil, Seq zero, a negative size, a side whose levels are not strictly ordered, which also rules out a repeated price) returns ErrInvalidDepthDelta before anything is read or changed. Every error leaves the book unchanged.

ApplyDelta is for one writer at a time, as the feed it follows is ordered.

func (*AggregatedBook) ApplySnapshot added in v0.7.0

func (ab *AggregatedBook) ApplySnapshot(snapshot *protocol.DepthDelta) error

ApplySnapshot resets the aggregated book state from a snapshot: the levels it lists and the version it carries. A snapshot is checked as a whole before anything changes. A negative size, or a price that appears twice on one side, returns ErrInvalidDepthDelta and leaves the book as it was. A zero size lists no level.

func (*AggregatedBook) Depth added in v0.7.0

func (ab *AggregatedBook) Depth(side Side, price udecimal.Decimal) (udecimal.Decimal, error)

Depth returns the aggregated size at a specific price level for the given side. Returns zero if the price level does not exist.

func (*AggregatedBook) GetDepth added in v0.9.0

func (ab *AggregatedBook) GetDepth(limit int) *protocol.GetDepthResponse

GetDepth returns the aggregated order book depth up to the specified limit.

func (*AggregatedBook) Rebuild added in v0.7.0

func (ab *AggregatedBook) Rebuild() error

Rebuild triggers a manual rebuild by calling the OnRebuild callback. Returns an error if OnRebuild is not set or if the callback fails.

func (*AggregatedBook) SequenceID added in v0.7.0

func (ab *AggregatedBook) SequenceID() uint64

SequenceID returns the depth version the book has reached. Used for synchronization and gap detection when a delta is applied.

type BusySpinIdleStrategy added in v0.9.0

type BusySpinIdleStrategy struct{}

BusySpinIdleStrategy spins without yielding.

func (BusySpinIdleStrategy) Idle added in v0.9.0

func (s BusySpinIdleStrategy) Idle()

Idle performs a busy-spin without yielding.

type CancelResult added in v0.9.0

type CancelResult struct {
	Batch      *LogBatch
	UserID     uint64
	FilledSize udecimal.Decimal
	Remaining  udecimal.Decimal
	Found      bool
}

CancelResult is what one cancel reports about the order it removed, from the call's single lookup. Batch is the call's logs. UserID, FilledSize and Remaining describe the order just before the cancel; they are zero when Found is false. Remaining is the order's total resting base size, visible plus hidden.

A found order whose UserID differs from the request's is refused as RejectReasonOrderNotFound with Found true: the book held the order, so a caller can tell a wrong owner from an order that is gone. A payload the book refuses before it cancels reports the order it found the same way, with the refusal's own reason.

type DepthChange added in v0.7.0

type DepthChange struct {
	Side     Side
	Price    udecimal.Decimal
	SizeDiff udecimal.Decimal
}

DepthChange represents a change in the order book depth.

func CalculateDepthChange added in v0.7.0

func CalculateDepthChange(log *OrderBookLog) DepthChange

CalculateDepthChange is the only rule for how a book log moves depth. It returns the side, the price level and the signed visible size change that the log causes. DepthDeltaBuilder applies this and nothing else, so a consumer and the matching book cannot disagree about the same log.

Only the visible quantities are read here: VisibleAdded for an open, MatchSize for a match and VisibleRemoved for a cancel or an amend. Remaining and OldRemaining are order totals (the visible part plus the hidden part) and depth does not count them. See OrderBookLog.

Note: For LogTypeMatch, the side returned is the Maker's side (opposite of the log's side).

type DepthDeltaBuilder added in v0.9.0

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

DepthDeltaBuilder produces the DepthDelta of the book logs it is given. It is the only producer of depth changes: which levels a log moves is decided by CalculateDepthChange, and the size each level reports is read from the book.

Usage: Add the logs of one or more SDK calls, then, before the next call changes the book, call Flush to read the levels, and Reset to forget them. Flush reads the book at the moment it is called, so the sizes it reports are the sizes that hold after the logs, not the sizes they were produced at. A caller that runs several calls before one Flush gets one delta holding each touched level once, at its final size.

Only logs that move visible depth are kept: a log whose CalculateDepthChange has a zero SizeDiff (a refusal, an admin or user event, a no-op amend, an amend that shrinks inside the hidden size) is ignored.

A builder is not safe for concurrent use. Steady-state Add, Flush and Reset with a reused DepthDelta do not allocate.

func NewDepthDeltaBuilder added in v0.9.0

func NewDepthDeltaBuilder() *DepthDeltaBuilder

NewDepthDeltaBuilder returns a builder with no logs.

func (*DepthDeltaBuilder) Add added in v0.9.0

func (b *DepthDeltaBuilder) Add(log *OrderBookLog)

Add records one book log. The log is copied out, not kept, so it may be released right after Add returns.

func (*DepthDeltaBuilder) AddBatch added in v0.9.0

func (b *DepthDeltaBuilder) AddBatch(logs []*OrderBookLog)

AddBatch records every log of a batch, in order.

func (*DepthDeltaBuilder) Flush added in v0.9.0

func (b *DepthDeltaBuilder) Flush(book *OrderBook, out *protocol.DepthDelta) bool

Flush fills out with the levels recorded so far, each at its size in book now, asks ascending and bids descending, and with the version of the last depth log. It reports false, and leaves out empty, when no visible depth moved. Flush does not change the builder; call Reset once the delta is taken.

out's slices are reused. A caller that keeps one DepthDelta across calls does not allocate once its slices have grown to the size of the largest delta.

func (*DepthDeltaBuilder) Reset added in v0.9.0

func (b *DepthDeltaBuilder) Reset()

Reset forgets every log recorded so far.

type DiscardPublishLog added in v0.7.0

type DiscardPublishLog struct{}

DiscardPublishLog is a publisher that ignores all logs.

func NewDiscardPublishLog added in v0.7.0

func NewDiscardPublishLog() *DiscardPublishLog

NewDiscardPublishLog creates a new DiscardPublishLog instance.

func (*DiscardPublishLog) Publish added in v0.7.0

func (p *DiscardPublishLog) Publish(_ []*OrderBookLog)

Publish does nothing.

type EventHandler added in v0.8.0

type EventHandler[T any] interface {
	OnEvent(event *T)
}

EventHandler is the interface for processing events from the RingBuffer.

type Future added in v0.9.0

type Future[T any] struct {
	// contains filtered or unexported fields
}

Future represents a placeholder for an asynchronous operation result.

func (*Future[T]) Wait added in v0.9.0

func (f *Future[T]) Wait(ctx context.Context) (T, error)

Wait blocks until the operation completes or the context is canceled.

type IdleStrategy added in v0.9.0

type IdleStrategy interface {
	Idle()
}

IdleStrategy defines a strategy for waiting during busy-spin loops.

type InputEvent added in v0.8.0

type InputEvent struct {
	// Request is the typed business request entering the write path.
	Request any

	// Internal Query fields (Read Path)
	Query any // e.g. *protocol.GetDepthRequest
	Resp  chan any
}

InputEvent is the internal wrapper for all events entering the OrderBook Actor.

type LogBatch added in v0.9.0

type LogBatch struct {
	Logs []*OrderBookLog
	// contains filtered or unexported fields
}

LogBatch is the logs one call produced, in the order the book produced them.

A book returns its own batch from PlaceOrder, CancelOrder and AmendOrder. The batch and the logs in it are valid until the next call on the same book, which reclaims them when it starts: the batch is emptied and the storage it points into is zeroed for reuse. A caller that keeps a log, or the Logs slice, past that next call reads storage that now belongs to another call. The same rule covers a Publisher (see Publisher): copy inside Publish.

type MarketSegment added in v0.8.0

type MarketSegment struct {
	MarketID string `json:"market_id"`
	Offset   int64  `json:"offset"`   // Start offset in snapshot.bin (relative to file start)
	Length   int64  `json:"length"`   // Length in bytes
	Checksum uint32 `json:"checksum"` // CRC32 Checksum of this segment
}

MarketSegment contains metadata for a specific market's data within the snapshot binary file.

type MatchingEngine

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

MatchingEngine manages multiple order books for different markets. It uses a single shared RingBuffer (Disruptor) for all commands, allowing the entire event loop to run on a single goroutine. This enables runtime.LockOSThread() for CPU affinity scenarios.

func NewMatchingEngine

func NewMatchingEngine(engineID string, publishTrader Publisher) *MatchingEngine

NewMatchingEngine creates a new matching engine instance.

func (*MatchingEngine) AmendOrderAsync added in v0.9.0

func (engine *MatchingEngine) AmendOrderAsync(ctx context.Context, req *protocol.AmendOrderRequest) error

AmendOrderAsync enqueues a typed amend-order request without waiting for execution.

func (*MatchingEngine) CancelOrderAsync added in v0.9.0

func (engine *MatchingEngine) CancelOrderAsync(ctx context.Context, req *protocol.CancelOrderRequest) error

CancelOrderAsync enqueues a typed cancel-order request without waiting for execution.

func (*MatchingEngine) GetDepth added in v0.9.0

func (engine *MatchingEngine) GetDepth(
	ctx context.Context,
	query *protocol.GetDepthQuery,
) (*Future[*protocol.GetDepthResponse], error)

GetDepth executes a read-only depth query against the matching engine.

func (*MatchingEngine) GetStats added in v0.8.0

func (engine *MatchingEngine) GetStats(
	ctx context.Context,
	query *protocol.GetStatsQuery,
) (*Future[*protocol.GetStatsResponse], error)

GetStats executes a read-only statistics query against the matching engine.

func (*MatchingEngine) PlaceOrderAsync added in v0.9.0

func (engine *MatchingEngine) PlaceOrderAsync(ctx context.Context, req *protocol.PlaceOrderRequest) error

PlaceOrderAsync enqueues a typed place-order request without waiting for execution.

func (*MatchingEngine) PlaceOrderBatchAsync added in v0.9.0

func (engine *MatchingEngine) PlaceOrderBatchAsync(
	ctx context.Context,
	reqs []*protocol.PlaceOrderRequest,
) error

PlaceOrderBatchAsync enqueues a batch of typed place-order requests without waiting for execution.

func (*MatchingEngine) RestoreFromSnapshot added in v0.8.0

func (engine *MatchingEngine) RestoreFromSnapshot(inputDir string) (*SnapshotMetadata, error)

RestoreFromSnapshot restores the entire matching engine state from a snapshot.

func (*MatchingEngine) Run added in v0.8.0

func (engine *MatchingEngine) Run() error

Run starts the engine's event loop. This is a blocking call. The consumer loop runs on the calling goroutine, enabling the caller to control thread affinity via runtime.LockOSThread().

Usage:

go func() {
    runtime.LockOSThread()
    defer runtime.UnlockOSThread()
    engine.Run()
}()

func (*MatchingEngine) SendUserEvent added in v0.8.0

func (engine *MatchingEngine) SendUserEvent(ctx context.Context, req *protocol.UserEventRequest) error

SendUserEvent enqueues a typed user event request without waiting for execution.

func (*MatchingEngine) Shutdown added in v0.7.0

func (engine *MatchingEngine) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the engine. It blocks until all pending commands in the RingBuffer are processed or the context is canceled.

func (*MatchingEngine) TakeSnapshot added in v0.8.0

func (engine *MatchingEngine) TakeSnapshot(
	ctx context.Context,
	outputDir string,
	timestamp ...int64,
) (*SnapshotMetadata, error)

TakeSnapshot captures a consistent snapshot of all order books and writes them to the specified directory. It generates two files: `snapshot.bin` (binary data) and `metadata.json` (metadata). The timestamp is the caller's logical time for the snapshot and is required: a call without a positive one returns ErrInvalidParam before anything is taken or written. Returns the metadata object or an error.

type MemoryPublishLog added in v0.7.0

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

MemoryPublishLog is an in-memory publisher for testing and simple use cases.

func NewMemoryPublishLog added in v0.7.0

func NewMemoryPublishLog() *MemoryPublishLog

NewMemoryPublishLog creates a new MemoryPublishLog instance.

func (*MemoryPublishLog) Count added in v0.7.0

func (p *MemoryPublishLog) Count() int

Count returns the number of captured logs.

func (*MemoryPublishLog) Get added in v0.7.0

func (p *MemoryPublishLog) Get(index int) *OrderBookLog

Get returns a log at the specific index.

func (*MemoryPublishLog) Logs added in v0.8.0

func (p *MemoryPublishLog) Logs() []*OrderBookLog

Logs returns all captured logs.

func (*MemoryPublishLog) Publish added in v0.7.0

func (p *MemoryPublishLog) Publish(logs []*OrderBookLog)

Publish adds the logs to the in-memory buffer.

type Order

type Order struct {
	ID        string           `json:"id"`
	Side      Side             `json:"side"`
	Price     udecimal.Decimal `json:"price"`
	Size      udecimal.Decimal `json:"size"` // Remaining visible size
	Type      OrderType        `json:"type"`
	UserID    uint64           `json:"user_id"`
	Timestamp int64            `json:"timestamp"` // Unix nano, creation time

	// Iceberg fields
	VisibleLimit udecimal.Decimal `json:"visible_limit,omitzero"`
	HiddenSize   udecimal.Decimal `json:"hidden_size,omitzero"`

	// Routing fields. The caller of PlaceOrder sets them and the book never reads them: it keeps them with the order
	// so that whoever settles a fill of this order can find its shard, fee rates and assets from the book alone.
	OmsShard     uint32           `json:"oms_shard"`
	MakerFeeRate udecimal.Decimal `json:"maker_fee_rate,omitzero"`
	TakerFeeRate udecimal.Decimal `json:"taker_fee_rate,omitzero"`
	BaseAsset    string           `json:"base_asset,omitempty"`
	QuoteAsset   string           `json:"quote_asset,omitempty"`
	// FilledSize is the base size this order has traded so far, over its whole life: each match adds to it, and an
	// amend does not change it.
	FilledSize udecimal.Decimal `json:"filled_size,omitzero"`

	// STPGroup and STPMode are the order's self-trade prevention. A taker's own mode decides what happens when it meets
	// a resting order of its user or group; the mode a resting order carries is read only when an amend makes it a
	// taker again. Zero STPGroup means no group.
	STPGroup uint64  `json:"stp_group,omitzero"`
	STPMode  STPMode `json:"stp_mode,omitzero"`
	// contains filtered or unexported fields
}

Order represents the state of an order in the order book. This is the serializable state used for snapshots.

type OrderBook

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

OrderBook is a pure logic object that maintains the state of an order book. It can be run directly (synchronously) or managed by a MatchingEngine event loop.

func NewOrderBook

func NewOrderBook(
	marketID string,
	opts ...OrderBookOption,
) *OrderBook

NewOrderBook creates a new pure OrderBook instance.

func (*OrderBook) AmendOrder added in v0.7.0

func (book *OrderBook) AmendOrder(req *protocol.AmendOrderRequest) (*LogBatch, error)

AmendOrder processes an order amendment synchronously and returns the resulting LogBatch. The batch belongs to the book: it and its logs are valid until the next call on this book, which reclaims them.

func (*OrderBook) BestPrice added in v0.9.0

func (book *OrderBook) BestPrice(side Side) (udecimal.Decimal, bool)

BestPrice returns the best price on side: the highest bid or the lowest ask. The second result is false when that side is empty. It does not allocate.

func (*OrderBook) CancelOrder

func (book *OrderBook) CancelOrder(req *protocol.CancelOrderRequest) (CancelResult, error)

CancelOrder processes an order cancellation synchronously and returns what the cancel did: the batch of logs and the order as the single lookup found it, just before the cancel removed it. The batch belongs to the book: it and its logs are valid until the next call on this book, which reclaims them.

func (*OrderBook) DepthCount added in v0.9.0

func (book *OrderBook) DepthCount(side Side) int

DepthCount is how many price levels rest on side: one per distinct price, however many orders queue there. It reads the count the queue keeps, so it does not allocate or walk the book. It is for a metrics reader that needs the size of the book without holding a second copy of it.

func (*OrderBook) EngineID added in v0.9.0

func (book *OrderBook) EngineID() string

EngineID returns the engine identifier for this order book.

func (*OrderBook) GetDepth added in v0.9.0

func (book *OrderBook) GetDepth(limit uint32) *protocol.GetDepthResponse

GetDepth returns the aggregated market depth up to the specified limit.

func (*OrderBook) LevelSize added in v0.9.0

func (book *OrderBook) LevelSize(side Side, price udecimal.Decimal) udecimal.Decimal

LevelSize returns the visible size resting at price on side: the depth of that level, not counting hidden iceberg size. It returns zero when no order rests there. It does not allocate.

func (*OrderBook) MarketID added in v0.9.0

func (book *OrderBook) MarketID() string

MarketID returns the market identifier for this order book.

func (*OrderBook) Order added in v0.9.0

func (book *OrderBook) Order(orderID string) (Order, bool)

Order returns a copy of the order with orderID as the book holds it now, and false when the book holds no such order. The copy is the book's current state: a later call changes the book, not the copy.

func (*OrderBook) OrderCount added in v0.9.0

func (book *OrderBook) OrderCount() int

OrderCount is how many orders rest on the book, on both sides. It does not allocate.

func (*OrderBook) PlaceOrder

func (book *OrderBook) PlaceOrder(req *protocol.PlaceOrderRequest) (*LogBatch, error)

PlaceOrder processes an order synchronously and returns the resulting LogBatch. The batch belongs to the book: it and its logs are valid until the next call on this book, which reclaims them.

func (*OrderBook) Remaining added in v0.9.0

func (book *OrderBook) Remaining(orderID string) (udecimal.Decimal, bool)

Remaining returns the total base size an order still has on the book: its visible part plus its hidden iceberg part. The second result is false when the book holds no order with that ID, which includes an order that has been filled or canceled. It does not allocate.

func (*OrderBook) Restore added in v0.8.0

func (book *OrderBook) Restore(snap *OrderBookSnapshot) error

Restore restores the order book state from a snapshot.

A snapshot does not carry the orders' canonical price keys, so Restore computes each one. A price whose coefficient needs more than 128 bits has no such key; the book refuses those at entry, so a snapshot holding one predates that rule. The same goes for a resting order without a self-trade prevention mode. Restore checks every order before it inserts any and returns an error wrapping ErrInvalidParam for such a snapshot, leaving the book as it was.

func (*OrderBook) SeqID added in v0.9.0

func (book *OrderBook) SeqID() uint64

SeqID returns the current book depth version: how many SDK calls have moved visible depth. A call that moves none, such as a refusal or an admin command, does not advance it.

func (*OrderBook) Snapshot added in v0.9.0

func (book *OrderBook) Snapshot() *OrderBookSnapshot

Snapshot creates and returns an in-memory snapshot of the current OrderBook state.

func (*OrderBook) TradeID added in v0.9.0

func (book *OrderBook) TradeID() uint64

TradeID returns the current trade ID counter of the order book.

type OrderBookLog added in v0.8.0

type OrderBookLog struct {
	// SeqID is the book depth version this log belongs to.
	//
	// One SDK call that moves visible depth advances the version by exactly one,
	// and every depth log of that call carries the new value: an open, a match, a
	// cancel or an amend, including the replenish open and the re-match of a
	// priority-losing amend. Hidden iceberg size is not depth, so a call that moves
	// only hidden size does not advance it. Refusals and admin commands carry 0.
	//
	// A no-op amend, and a shrink that stays inside the hidden size, move no visible
	// depth; they carry the current version, which the call did not advance.
	//
	// The consequence worth knowing: a consumer that follows depth through
	// DepthDeltaBuilder and AggregatedBook.ApplyDelta sees one version per call, with
	// no version used up by a refusal, so a version jump is a lost update and not
	// the side effect of a rejected order.
	//
	// It is not a timestamp and not comparable across markets - the counter
	// belongs to one order book.
	//
	// SeqID is 0 for LogTypeUser: a user event moves no depth and has no depth
	// version.
	SeqID     uint64           `json:"seq_id"`
	CommandID string           `json:"command_id"`
	EngineID  string           `json:"engine_id"`
	TradeID   uint64           `json:"trade_id,omitempty"`
	Type      protocol.LogType `json:"type"`
	MarketID  string           `json:"market_id"`
	Side      Side             `json:"side"`
	Price     udecimal.Decimal `json:"price"`
	Amount    udecimal.Decimal `json:"amount"`
	OrderID   string           `json:"order_id"`
	UserID    uint64           `json:"user_id"`
	OrderType OrderType        `json:"order_type"`
	OldPrice  udecimal.Decimal `json:"old_price"`
	// The quantity fields below each have one meaning. A log that does not use a
	// field leaves it zero, and the table in the README says which log fills which.
	//
	// MatchSize is the base quantity a Match log trades. A match consumes only the
	// visible part of the maker, so it is also the visible size the maker gives up.
	MatchSize udecimal.Decimal `json:"match_size,omitzero"`
	// Remaining is the order's total remaining base size, visible plus hidden. An
	// Open carries it after the order rests, an Amend its new total, and a Cancel
	// the total the cancel removes. A Reject carries the base quantity the order did
	// not get.
	Remaining udecimal.Decimal `json:"remaining,omitzero"`
	// OldRemaining is an Amend's total before the amend. Zero on every other log.
	OldRemaining udecimal.Decimal `json:"old_remaining,omitzero"`
	// VisibleAdded is the visible size an Open puts on the book: the visible part
	// of Remaining. The hidden part of an iceberg is never depth.
	VisibleAdded udecimal.Decimal `json:"visible_added,omitzero"`
	// VisibleRemoved is the visible (depth) size a Cancel or an Amend takes off the
	// book.
	VisibleRemoved udecimal.Decimal `json:"visible_removed,omitzero"`
	// QuoteRemaining is the quote a Reject of a quote-sized market order leaves
	// unspent. Zero on every other log, including a base-sized reject.
	QuoteRemaining udecimal.Decimal `json:"quote_remaining,omitzero"`
	// MakerOrder is the maker of a Match log as the trade left it: a copy of its ID, user, routing and size, filled and
	// hidden after this trade and before any replenish it triggers. It is the one place a match names its maker: read
	// the maker's ID and user from MakerOrder.ID and MakerOrder.UserID. A Cancel log with CancelReason stp fills it too, for
	// the same reason: only it carries the order's routing and filled size. Zero on every other log.
	MakerOrder Order `json:"maker_order,omitzero"`
	// CancelReason is why a Cancel log removed its order: the owner asked (user) or the book prevented a self trade
	// (stp). Empty on every other log. An stp cancel also carries the canceled order in MakerOrder, which holds its
	// routing and filled size.
	CancelReason protocol.CancelReason `json:"cancel_reason,omitempty"`
	RejectReason protocol.RejectReason `json:"reject_reason,omitempty"`
	EventType    string                `json:"event_type,omitempty"` // For Admin/User events
	Data         []byte                `json:"data,omitempty"`       // For User events
	Timestamp    int64                 `json:"timestamp"`
}

OrderBookLog represents a single event in the order book's history. OrderBookLog is one thing the order book did. Only depth-changing events carry a SeqID; see the field's own note.

func NewAdminLog added in v0.8.0

func NewAdminLog(
	seqID uint64,
	commandID, engineID, marketID string,
	userID uint64,
	eventType string,
	timestamp int64,
) *OrderBookLog

NewAdminLog creates a new OrderBookLog for a successful management event.

func NewAmendLog added in v0.8.0

func NewAmendLog(
	seqID uint64,
	commandID, engineID, marketID string,
	orderID string,
	userID uint64,
	side Side,
	price, remaining udecimal.Decimal,
	oldPrice udecimal.Decimal,
	oldRemaining udecimal.Decimal,
	orderType OrderType,
	timestamp int64,
) *OrderBookLog

NewAmendLog creates a new OrderBookLog for an order amendment event. remaining is the order's total after the amend, oldRemaining its total before. The caller sets VisibleRemoved.

func NewCancelLog added in v0.8.0

func NewCancelLog(
	seqID uint64,
	commandID, engineID, marketID string,
	orderID string,
	userID uint64,
	side Side,
	price, remaining udecimal.Decimal,
	orderType OrderType,
	timestamp int64,
) *OrderBookLog

NewCancelLog creates a new OrderBookLog for an order cancellation event. remaining is the order's total before the cancel. The caller sets VisibleRemoved.

func NewMatchLog added in v0.8.0

func NewMatchLog(
	seqID uint64,
	commandID, engineID string,
	tradeID uint64,
	marketID string,
	takerID string,
	takerUserID uint64,
	takerSide Side,
	takerType OrderType,
	maker *Order,
	price udecimal.Decimal,
	matchSize udecimal.Decimal,
	timestamp int64,
) *OrderBookLog

NewMatchLog creates a new OrderBookLog for a trade match event. maker is the resting order as the trade left it; the log keeps a copy in MakerOrder.

func NewOpenLog added in v0.8.0

func NewOpenLog(
	seqID uint64,
	commandID, engineID, marketID string,
	orderID string,
	userID uint64,
	side Side,
	price, visible, remaining udecimal.Decimal,
	orderType OrderType,
	timestamp int64,
) *OrderBookLog

NewOpenLog creates a new OrderBookLog for an open order event. visible is the visible size the order puts on the book and remaining its total, visible plus hidden.

func NewRejectLog added in v0.8.0

func NewRejectLog(
	seqID uint64,
	commandID, engineID, marketID string,
	orderID string,
	userID uint64,
	reason protocol.RejectReason,
	timestamp int64,
) *OrderBookLog

NewRejectLog creates a new OrderBookLog for an order rejection event.

func NewUserEventLog added in v0.8.0

func NewUserEventLog(
	commandID, engineID string,
	userID uint64,
	eventType string,
	key string,
	data []byte,
	timestamp int64,
) *OrderBookLog

NewUserEventLog creates a new OrderBookLog for a generic user event. Its SeqID stays 0: a user event moves no depth.

type OrderBookOption added in v0.8.0

type OrderBookOption func(*OrderBook)

OrderBookOption configures an OrderBook.

func WithEngineID added in v0.9.0

func WithEngineID(id string) OrderBookOption

WithEngineID sets the engine ID for the order book.

func WithPublisher added in v0.9.0

func WithPublisher(publisher Publisher) OrderBookOption

WithPublisher sets the publisher for the order book.

func WithSkiplistSeed added in v0.9.0

func WithSkiplistSeed(seed int64) OrderBookOption

WithSkiplistSeed sets the skiplist PRNG seed for deterministic queue ordering.

type OrderBookSnapshot added in v0.8.0

type OrderBookSnapshot struct {
	MarketID string `json:"market_id"`
	// SeqID is the book depth version this snapshot was taken at. It advances once
	// per SDK call that moves visible depth, so restoring this value lets the book
	// resume the version a downstream reader is already following.
	SeqID   uint64   `json:"seq_id"`
	TradeID uint64   `json:"trade_id"` // Current Trade sequence ID
	Bids    []*Order `json:"bids"`     // Ordered list of bids (best price first)
	Asks    []*Order `json:"asks"`     // Ordered list of asks (best price first)
}

OrderBookSnapshot contains the full state of a single OrderBook.

type OrderType

type OrderType = protocol.OrderType

OrderType represents the type of order.

const (
	// Market order.
	Market OrderType = protocol.OrderTypeMarket
	// Limit order.
	Limit OrderType = protocol.OrderTypeLimit
	// FOK order (Fill or Kill).
	FOK OrderType = protocol.OrderTypeFOK
	// IOC order (Immediate or Cancel).
	IOC OrderType = protocol.OrderTypeIOC
	// PostOnly order.
	PostOnly OrderType = protocol.OrderTypePostOnly
	// Cancel order.
	Cancel OrderType = protocol.OrderTypeCancel
)

type Publisher added in v0.9.0

type Publisher interface {
	Publish(logs []*OrderBookLog)
}

Publisher is the interface for receiving order book logs.

Ownership: the logs passed to Publish belong to the book or engine that produced them. They stay valid until that book's next call (or the engine's next event), which reclaims them, so an implementation that needs the logs beyond the call - to hand them to a channel, a goroutine, or a queue - must copy them before returning.

An implementation cannot reclaim the logs itself: Publish receives the slice, not the *LogBatch it belongs to. A publisher that retains the slice without copying is a silent-corruption bug, not a slow path.

type RebuildFunc added in v0.7.0

type RebuildFunc func() (*protocol.DepthDelta, error)

RebuildFunc is the callback type for fetching a snapshot during rebuild. Implementations should fetch the current order book snapshot from external sources (e.g., Redis, Database, API) and return it for the AggregatedBook to apply.

A snapshot is a protocol.DepthDelta that lists every level of the book: Seq is the version the snapshot was taken at, and the levels are the same type ApplyDelta takes.

type RingBuffer added in v0.8.0

type RingBuffer[T any] struct {
	// contains filtered or unexported fields
}

RingBuffer is a lock-free MPSC (Multi-Producer Single-Consumer) ring buffer. It provides high-throughput, zero-allocation event passing between goroutines.

func NewRingBuffer added in v0.8.0

func NewRingBuffer[T any](capacity int64, handler EventHandler[T]) *RingBuffer[T]

NewRingBuffer creates a new MPSC RingBuffer. The capacity must be a power of 2.

func (*RingBuffer[T]) Claim added in v0.8.0

func (rb *RingBuffer[T]) Claim() (int64, *T)

Claim atomically claims a sequence and returns a pointer to the slot. Returns (-1, nil) if the RingBuffer is shut down. The caller should write to the slot and then call Commit(seq).

func (*RingBuffer[T]) ClaimN added in v0.8.0

func (rb *RingBuffer[T]) ClaimN(n int64) (start int64, end int64)

ClaimN atomically claims n sequences and returns the start and end sequence numbers. Returns (-1, -1) if the RingBuffer is shut down. The caller should write to the slots from startSeq to endSeq and then call CommitN(startSeq, endSeq).

func (*RingBuffer[T]) Commit added in v0.8.0

func (rb *RingBuffer[T]) Commit(seq int64)

Commit marks the slot as published, making it visible to the consumer.

func (*RingBuffer[T]) CommitN added in v0.8.0

func (rb *RingBuffer[T]) CommitN(startSeq int64, endSeq int64)

CommitN marks the slots from startSeq to endSeq as published, making them visible to the consumer.

func (*RingBuffer[T]) ConsumerSequence added in v0.8.0

func (rb *RingBuffer[T]) ConsumerSequence() int64

ConsumerSequence returns the current consumer sequence (for monitoring).

func (*RingBuffer[T]) GetPendingEvents added in v0.8.0

func (rb *RingBuffer[T]) GetPendingEvents() int64

GetPendingEvents returns the number of pending events (for monitoring).

func (*RingBuffer[T]) ProducerSequence added in v0.8.0

func (rb *RingBuffer[T]) ProducerSequence() int64

ProducerSequence returns the current producer sequence (for monitoring).

func (*RingBuffer[T]) Publish added in v0.8.0

func (rb *RingBuffer[T]) Publish(event T)

Publish publishes an event to the ring buffer (multi-producer safe). This is a convenience method that wraps Claim() and Commit().

func (*RingBuffer[T]) Run added in v0.8.0

func (rb *RingBuffer[T]) Run()

Run starts the consumer loop in the calling goroutine (blocking). This allows the caller to control the goroutine and OS thread, enabling runtime.LockOSThread() for CPU affinity scenarios.

func (*RingBuffer[T]) Shutdown added in v0.8.0

func (rb *RingBuffer[T]) Shutdown(ctx context.Context) error

Shutdown gracefully stops the disruptor, ensuring all pending events are processed. It blocks until all events are processed or the context is canceled.

func (*RingBuffer[T]) TryClaim added in v0.9.0

func (rb *RingBuffer[T]) TryClaim() (int64, *T)

TryClaim atomically tries to claim a sequence and returns a pointer to the slot. Returns (-1, nil) if the RingBuffer is full or shut down.

func (*RingBuffer[T]) TryClaimN added in v0.9.0

func (rb *RingBuffer[T]) TryClaimN(n int64) (start int64, end int64)

TryClaimN atomically tries to claim n sequences and returns the start and end sequence numbers. Returns (-1, -1) if the RingBuffer is full, CAS fails, or shut down.

type STPMode added in v0.9.0

type STPMode = protocol.STPMode

STPMode is how a taker reacts to a resting order of the same user or STP group.

type Side

type Side = protocol.Side

Side represents the order side (Buy or Sell).

const (
	// Buy side.
	Buy Side = protocol.SideBuy
	// Sell side.
	Sell Side = protocol.SideSell
)

type SnapshotFileFooter added in v0.8.0

type SnapshotFileFooter struct {
	Markets []MarketSegment `json:"markets"` // Index of market data in this file
}

SnapshotFileFooter is the footer structure stored at the end of snapshot.bin. Layout: [BinaryData...][FooterJSON][FooterLength(4 bytes)].

type SnapshotMetadata added in v0.8.0

type SnapshotMetadata struct {
	SchemaVersion    int    `json:"schema_version"`    // Snapshot schema version for backward compatibility
	Timestamp        int64  `json:"timestamp"`         // Logical timestamp the caller gave; required, never derived
	EngineVersion    string `json:"engine_version"`    // Engine version
	SnapshotChecksum uint32 `json:"snapshot_checksum"` // CRC32 of the entire snapshot.bin file
}

SnapshotMetadata holds the global metadata for a snapshot (stored in metadata.json).

type UpdateEvent

type UpdateEvent struct {
	Price string `json:"price"`
	Size  string `json:"size"`
}

UpdateEvent represents a change in price or size at a specific price level.

type YieldingIdleStrategy added in v0.9.0

type YieldingIdleStrategy struct{}

YieldingIdleStrategy yields the CPU to other goroutines.

func (YieldingIdleStrategy) Idle added in v0.9.0

func (s YieldingIdleStrategy) Idle()

Idle yields the CPU using runtime.Gosched().

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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