Documentation
¶
Index ¶
- Constants
- Variables
- type AggregatedBook
- func (ab *AggregatedBook) ApplyDelta(d *protocol.DepthDelta) error
- func (ab *AggregatedBook) ApplySnapshot(snapshot *protocol.DepthDelta) error
- func (ab *AggregatedBook) Depth(side Side, price udecimal.Decimal) (udecimal.Decimal, error)
- func (ab *AggregatedBook) GetDepth(limit int) *protocol.GetDepthResponse
- func (ab *AggregatedBook) Rebuild() error
- func (ab *AggregatedBook) SequenceID() uint64
- type BusySpinIdleStrategy
- type CancelResult
- type DepthChange
- type DepthDeltaBuilder
- type DiscardPublishLog
- type EventHandler
- type Future
- type IdleStrategy
- type InputEvent
- type LogBatch
- type MarketSegment
- type MatchingEngine
- func (engine *MatchingEngine) AmendOrderAsync(ctx context.Context, req *protocol.AmendOrderRequest) error
- func (engine *MatchingEngine) CancelOrderAsync(ctx context.Context, req *protocol.CancelOrderRequest) error
- func (engine *MatchingEngine) GetDepth(ctx context.Context, query *protocol.GetDepthQuery) (*Future[*protocol.GetDepthResponse], error)
- func (engine *MatchingEngine) GetStats(ctx context.Context, query *protocol.GetStatsQuery) (*Future[*protocol.GetStatsResponse], error)
- func (engine *MatchingEngine) PlaceOrderAsync(ctx context.Context, req *protocol.PlaceOrderRequest) error
- func (engine *MatchingEngine) PlaceOrderBatchAsync(ctx context.Context, reqs []*protocol.PlaceOrderRequest) error
- func (engine *MatchingEngine) RestoreFromSnapshot(inputDir string) (*SnapshotMetadata, error)
- func (engine *MatchingEngine) Run() error
- func (engine *MatchingEngine) SendUserEvent(ctx context.Context, req *protocol.UserEventRequest) error
- func (engine *MatchingEngine) Shutdown(ctx context.Context) error
- func (engine *MatchingEngine) TakeSnapshot(ctx context.Context, outputDir string, timestamp ...int64) (*SnapshotMetadata, error)
- type MemoryPublishLog
- type Order
- type OrderBook
- func (book *OrderBook) AmendOrder(req *protocol.AmendOrderRequest) (*LogBatch, error)
- func (book *OrderBook) BestPrice(side Side) (udecimal.Decimal, bool)
- func (book *OrderBook) CancelOrder(req *protocol.CancelOrderRequest) (CancelResult, error)
- func (book *OrderBook) DepthCount(side Side) int
- func (book *OrderBook) EngineID() string
- func (book *OrderBook) GetDepth(limit uint32) *protocol.GetDepthResponse
- func (book *OrderBook) LevelSize(side Side, price udecimal.Decimal) udecimal.Decimal
- func (book *OrderBook) MarketID() string
- func (book *OrderBook) Order(orderID string) (Order, bool)
- func (book *OrderBook) OrderCount() int
- func (book *OrderBook) PlaceOrder(req *protocol.PlaceOrderRequest) (*LogBatch, error)
- func (book *OrderBook) Remaining(orderID string) (udecimal.Decimal, bool)
- func (book *OrderBook) Restore(snap *OrderBookSnapshot) error
- func (book *OrderBook) SeqID() uint64
- func (book *OrderBook) Snapshot() *OrderBookSnapshot
- func (book *OrderBook) TradeID() uint64
- type OrderBookLog
- func NewAdminLog(seqID uint64, commandID, engineID, marketID string, userID uint64, ...) *OrderBookLog
- func NewAmendLog(seqID uint64, commandID, engineID, marketID string, orderID string, ...) *OrderBookLog
- func NewCancelLog(seqID uint64, commandID, engineID, marketID string, orderID string, ...) *OrderBookLog
- func NewMatchLog(seqID uint64, commandID, engineID string, tradeID uint64, marketID string, ...) *OrderBookLog
- func NewOpenLog(seqID uint64, commandID, engineID, marketID string, orderID string, ...) *OrderBookLog
- func NewRejectLog(seqID uint64, commandID, engineID, marketID string, orderID string, ...) *OrderBookLog
- func NewUserEventLog(commandID, engineID string, userID uint64, eventType string, key string, ...) *OrderBookLog
- type OrderBookOption
- type OrderBookSnapshot
- type OrderType
- type Publisher
- type RebuildFunc
- type RingBuffer
- func (rb *RingBuffer[T]) Claim() (int64, *T)
- func (rb *RingBuffer[T]) ClaimN(n int64) (start int64, end int64)
- func (rb *RingBuffer[T]) Commit(seq int64)
- func (rb *RingBuffer[T]) CommitN(startSeq int64, endSeq int64)
- func (rb *RingBuffer[T]) ConsumerSequence() int64
- func (rb *RingBuffer[T]) GetPendingEvents() int64
- func (rb *RingBuffer[T]) ProducerSequence() int64
- func (rb *RingBuffer[T]) Publish(event T)
- func (rb *RingBuffer[T]) Run()
- func (rb *RingBuffer[T]) Shutdown(ctx context.Context) error
- func (rb *RingBuffer[T]) TryClaim() (int64, *T)
- func (rb *RingBuffer[T]) TryClaimN(n int64) (start int64, end int64)
- type STPMode
- type Side
- type SnapshotFileFooter
- type SnapshotMetadata
- type UpdateEvent
- type YieldingIdleStrategy
Constants ¶
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 ¶
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") )
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
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
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.
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
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
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
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
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
MarketID returns the market identifier for this order book.
func (*OrderBook) Order ¶ added in v0.9.0
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
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
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
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.
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 ¶
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.
type STPMode ¶ added in v0.9.0
STPMode is how a taker reacts to a resting order of the same user or STP group.
type SnapshotFileFooter ¶ added in v0.8.0
type SnapshotFileFooter struct {
}
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 ¶
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().