engine

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package engine provides the core matching engine and multi-market orchestration.

The MatchingEngine manages multiple markets, each with its own order book and matcher. It provides async APIs using the Future pattern for all operations, with context support for cancellation and timeouts.

Key features:

  • Multi-market support with isolation
  • Async API with Future pattern
  • Market state management (running/suspended/halted)
  • Snapshot and restore for disaster recovery
  • Event-driven architecture with ring buffer

Example usage:

publisher := event.NewChannelPublisher(10000)
engine := engine.NewMatchingEngine(publisher)
engine.Start()
defer engine.Stop()

// Create market
ctx := context.Background()
req := &protocol.CreateMarketRequest{
    BaseCommand: protocol.BaseCommand{
        CommandID: "cmd-1",
        UserID:    1000,
        MarketID:  "BTC-USDT",
        Timestamp: time.Now().UnixNano(),
    },
    MinLotSize: decimal.NewFromFloat(0.001),
}
future, _ := engine.CreateMarket(ctx, req)
success, err := future.Wait(ctx)

Index

Constants

This section is empty.

Variables

View Source
var DefaultLotSize = decimal.NewFromFloat(0.00000001) // 0.00000001

DefaultLotSize is the minimum trade unit (1e-8) This prevents infinite loops in market order quote mode

Functions

This section is empty.

Types

type Config

type Config struct {
	Symbol string

	RingBufferSize uint64

	// MinLotSize is the minimum executable trade unit
	// Market orders with matchSize < MinLotSize will be rejected
	// Default: 1e-8 (0.00000001)
	MinLotSize decimal.Decimal
}

type Engine

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

func New

func New(config Config) *Engine

func (*Engine) Events

func (e *Engine) Events() <-chan *event.OrderBookLog

Events returns the event log channel

func (*Engine) GetLastCmdSeqID

func (e *Engine) GetLastCmdSeqID() uint64

GetLastCmdSeqID returns the last processed command SeqID Used for replay checkpoint after snapshot restore

func (*Engine) GetMatcher

func (e *Engine) GetMatcher() *matcher.Matcher

GetMatcher returns the matcher for snapshot purposes

func (*Engine) GetOrderBook

func (e *Engine) GetOrderBook() *book.OrderBook

func (*Engine) GetState

func (e *Engine) GetState() protocol.OrderBookState

GetState returns the current market state

func (*Engine) HaltMarket

func (e *Engine) HaltMarket(reason string)

HaltMarket halts the market (emergency stop, no operations)

func (*Engine) IsRunning

func (e *Engine) IsRunning() bool

func (*Engine) ResumeMarket

func (e *Engine) ResumeMarket(reason string)

ResumeMarket resumes the market to running state

func (*Engine) SetLastCmdSeqID

func (e *Engine) SetLastCmdSeqID(seqID uint64)

SetLastCmdSeqID sets the last processed command SeqID Used when restoring from snapshot

func (*Engine) Start

func (e *Engine) Start()

func (*Engine) Stop

func (e *Engine) Stop()

func (*Engine) SubmitOrder

func (e *Engine) SubmitOrder(o *order.Order) bool

func (*Engine) SuspendMarket

func (e *Engine) SuspendMarket(reason string)

SuspendMarket suspends the market (no new orders, can cancel existing)

type Future

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

Future represents a placeholder for an asynchronous operation result

func NewFuture

func NewFuture[T any]() *Future[T]

NewFuture creates a new Future

func (*Future[T]) Complete

func (f *Future[T]) Complete(value T)

Complete completes the future with a value

func (*Future[T]) Fail

func (f *Future[T]) Fail(err error)

Fail completes the future with an error

func (*Future[T]) IsDone

func (f *Future[T]) IsDone() bool

IsDone returns true if the future has been completed

func (*Future[T]) Wait

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

Wait blocks until the future is completed or context is cancelled Returns the value and any error

type Market

type Market struct {
	ID         string
	OrderBook  *book.OrderBook
	Matcher    *matcher.Matcher
	State      protocol.OrderBookState
	MinLotSize decimal.Decimal
	// contains filtered or unexported fields
}

Market represents a single trading market with its own order book

func NewMarket

func NewMarket(
	id string,
	minLotSize decimal.Decimal,
	seqGen *event.SequenceGenerator,
	publisher event.PublishLog,
) *Market

NewMarket creates a new market

func (*Market) CanAmendOrder

func (m *Market) CanAmendOrder() bool

CanAmendOrder returns true if orders can be amended

func (*Market) CanCancelOrder

func (m *Market) CanCancelOrder() bool

CanCancelOrder returns true if orders can be cancelled

func (*Market) CanPlaceOrder

func (m *Market) CanPlaceOrder() bool

CanPlaceOrder returns true if new orders can be placed

func (*Market) GetState

func (m *Market) GetState() protocol.OrderBookState

GetState returns the current market state (thread-safe)

func (*Market) SetState

func (m *Market) SetState(state protocol.OrderBookState)

SetState sets the market state (thread-safe)

func (*Market) UpdateConfig

func (m *Market) UpdateConfig(minLotSize decimal.Decimal)

UpdateConfig updates market configuration

type MatchingEngine

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

MatchingEngine manages multiple markets and routes commands

func NewMatchingEngine

func NewMatchingEngine(publisher event.PublishLog) *MatchingEngine

NewMatchingEngine creates a new matching engine

func (*MatchingEngine) AmendOrderAsync

AmendOrderAsync amends an existing order asynchronously

func (*MatchingEngine) CancelOrderAsync

CancelOrderAsync cancels an existing order asynchronously

func (*MatchingEngine) CreateMarket

func (e *MatchingEngine) CreateMarket(ctx context.Context, req *protocol.CreateMarketRequest) (*Future[bool], error)

CreateMarket creates a new market

func (*MatchingEngine) GetMarket

func (e *MatchingEngine) GetMarket(marketID string) (*Market, error)

GetMarket retrieves a market by ID

func (*MatchingEngine) GetStats

func (e *MatchingEngine) GetStats(marketID string) (*protocol.MarketStats, error)

GetStats returns market statistics

func (*MatchingEngine) PlaceOrderAsync

PlaceOrderAsync places a new order asynchronously

func (*MatchingEngine) RestoreFromFile

func (e *MatchingEngine) RestoreFromFile(snapshotDir string) (*snapshot.SnapshotMetadata, error)

RestoreFromFile reads a snapshot from disk and restores engine state

func (*MatchingEngine) RestoreFromSnapshot

func (e *MatchingEngine) RestoreFromSnapshot(snapshots []*OrderBookSnapshot) error

RestoreFromSnapshot restores engine state from snapshots

func (*MatchingEngine) ResumeMarket

func (e *MatchingEngine) ResumeMarket(ctx context.Context, req *protocol.ResumeMarketRequest) (*Future[bool], error)

ResumeMarket resumes trading on a market

func (*MatchingEngine) Shutdown

func (e *MatchingEngine) Shutdown()

Shutdown gracefully shuts down the engine

func (*MatchingEngine) SuspendMarket

func (e *MatchingEngine) SuspendMarket(ctx context.Context, req *protocol.SuspendMarketRequest) (*Future[bool], error)

SuspendMarket suspends trading on a market

func (*MatchingEngine) TakeSnapshot

func (e *MatchingEngine) TakeSnapshot() ([]*OrderBookSnapshot, uint64)

TakeSnapshot creates a point-in-time snapshot of all markets

func (*MatchingEngine) TakeSnapshotToFile

func (e *MatchingEngine) TakeSnapshotToFile(targetDir string) (string, error)

TakeSnapshotToFile takes a snapshot and saves it to disk atomically

func (*MatchingEngine) UpdateConfig

func (e *MatchingEngine) UpdateConfig(ctx context.Context, req *protocol.UpdateConfigRequest) (*Future[bool], error)

UpdateConfig updates market configuration

type OrderBookSnapshot

type OrderBookSnapshot = snapshot.OrderBookSnapshot

Alias for cleaner code

Jump to

Keyboard shortcuts

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