Help us shape the future of Go! Take the 2026 Go Developer Survey

orderbook

package
v1.24.29 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

Documentation

Overview

Package orderbook implements a high-performance order book for the DEX VM.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInsufficientLiquidity = errors.New("insufficient liquidity")
	ErrOrderNotFound         = errors.New("order not found")
	ErrInvalidPrice          = errors.New("invalid price")
	ErrInvalidQuantity       = errors.New("invalid quantity")
	ErrOrderExpired          = errors.New("order expired")
	ErrSelfTrade             = errors.New("self-trade not allowed")
)
View Source
var (
	ErrIcebergDisplayTooLarge = errors.New("iceberg display size exceeds total")
	ErrIcebergDisplayTooSmall = errors.New("iceberg display size must be positive")
	ErrHiddenOrderNotAllowed  = errors.New("hidden orders not allowed for this market")
	ErrPegOffsetInvalid       = errors.New("peg offset invalid")
	ErrTrailAmountInvalid     = errors.New("trail amount must be positive")
)
View Source
var (
	ErrStopPriceRequired = errors.New("stop price required for stop orders")
	ErrStopOrderNotFound = errors.New("stop order not found")
	ErrStopAlreadyActive = errors.New("stop order already triggered")
)

Functions

This section is empty.

Types

type AdvancedOrderbook added in v1.22.76

type AdvancedOrderbook struct {
	*Orderbook
	// contains filtered or unexported fields
}

AdvancedOrderbook extends Orderbook with advanced order type support

func NewAdvancedOrderbook added in v1.22.76

func NewAdvancedOrderbook(symbol string, allowHidden, allowIceberg bool) *AdvancedOrderbook

NewAdvancedOrderbook creates an orderbook with advanced order support

func (*AdvancedOrderbook) AddHiddenOrder added in v1.22.76

func (aob *AdvancedOrderbook) AddHiddenOrder(order *Order) ([]*Trade, error)

AddHiddenOrder adds a hidden order to the book

func (*AdvancedOrderbook) AddIcebergOrder added in v1.22.76

func (aob *AdvancedOrderbook) AddIcebergOrder(order *Order, displaySize uint64) ([]*Trade, error)

AddIcebergOrder adds an iceberg order to the book

func (*AdvancedOrderbook) AddTrailingStop added in v1.22.76

func (aob *AdvancedOrderbook) AddTrailingStop(order *Order, trailAmount, trailPercent uint64) error

AddTrailingStop adds a trailing stop order

func (*AdvancedOrderbook) GetDepthWithHidden added in v1.22.76

func (aob *AdvancedOrderbook) GetDepthWithHidden(maxLevels int, includeHidden bool) (bids, asks []*PriceLevel)

GetDepthWithHidden returns depth including/excluding hidden orders

func (*AdvancedOrderbook) GetHiddenOrderCount added in v1.22.76

func (aob *AdvancedOrderbook) GetHiddenOrderCount() int

GetHiddenOrderCount returns the number of hidden orders

func (*AdvancedOrderbook) GetIcebergStats added in v1.22.76

func (aob *AdvancedOrderbook) GetIcebergStats() (count int, totalHidden uint64)

GetIcebergStats returns statistics about iceberg orders

func (*AdvancedOrderbook) UpdatePeggedOrders added in v1.22.76

func (aob *AdvancedOrderbook) UpdatePeggedOrders()

UpdatePeggedOrders updates all pegged order prices

func (*AdvancedOrderbook) UpdateTrailingStops added in v1.22.76

func (aob *AdvancedOrderbook) UpdateTrailingStops(currentPrice uint64) []*Order

UpdateTrailingStops updates all trailing stop prices based on current market

type HiddenOrder added in v1.22.76

type HiddenOrder struct {
	*Order

	// Hidden flag
	IsHidden bool `json:"isHidden"`

	// MinDisplayQuantity for partially hidden orders
	MinDisplayQuantity uint64 `json:"minDisplayQty"`
}

HiddenOrder represents a fully hidden order

func NewHiddenOrder added in v1.22.76

func NewHiddenOrder(order *Order) *HiddenOrder

NewHiddenOrder creates a new hidden order

type IcebergOrder added in v1.22.76

type IcebergOrder struct {
	*Order

	// TotalSize is the full hidden size of the order
	TotalSize uint64 `json:"totalSize"`

	// DisplaySize is the visible portion
	DisplaySize uint64 `json:"displaySize"`

	// RemainingHiddenSize is what's left in the hidden pool
	RemainingHiddenSize uint64 `json:"remainingHiddenSize"`

	// RefillCount tracks how many times the order has been refilled
	RefillCount int `json:"refillCount"`
}

IcebergOrder extends Order with iceberg-specific fields

func NewIcebergOrder added in v1.22.76

func NewIcebergOrder(order *Order, displaySize uint64) (*IcebergOrder, error)

NewIcebergOrder creates a new iceberg order

func (*IcebergOrder) NeedsRefill added in v1.22.76

func (io *IcebergOrder) NeedsRefill() bool

NeedsRefill returns true if the visible portion is depleted but hidden remains

func (*IcebergOrder) Refill added in v1.22.76

func (io *IcebergOrder) Refill() uint64

Refill replenishes the visible portion from the hidden pool

func (*IcebergOrder) VisibleQuantity added in v1.22.76

func (io *IcebergOrder) VisibleQuantity() uint64

VisibleQuantity returns the quantity visible in the order book

type OCOEngine added in v1.22.76

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

OCOEngine manages OCO (One-Cancels-Other) order pairs

func NewOCOEngine added in v1.22.76

func NewOCOEngine(cancelCallback func(orderID ids.ID) error) *OCOEngine

NewOCOEngine creates a new OCO engine

func (*OCOEngine) CancelOCO added in v1.22.76

func (oe *OCOEngine) CancelOCO(ocoID ids.ID) error

CancelOCO cancels both sides of an OCO

func (*OCOEngine) CreateOCO added in v1.22.76

func (oe *OCOEngine) CreateOCO(primaryID, secondaryID ids.ID, symbol string, owner ids.ShortID) (*OCOOrder, error)

CreateOCO creates a new OCO pair

func (*OCOEngine) GetOCO added in v1.22.76

func (oe *OCOEngine) GetOCO(ocoID ids.ID) *OCOOrder

GetOCO returns an OCO by ID

func (*OCOEngine) GetOCOByOrder added in v1.22.76

func (oe *OCOEngine) GetOCOByOrder(orderID ids.ID) *OCOOrder

GetOCOByOrder returns the OCO containing a specific order

func (*OCOEngine) OnOrderFilled added in v1.22.76

func (oe *OCOEngine) OnOrderFilled(orderID ids.ID) error

OnOrderFilled handles when one side of an OCO is filled/triggered

type OCOOrder added in v1.22.76

type OCOOrder struct {
	ID          ids.ID      `json:"id"`
	PrimaryID   ids.ID      `json:"primaryId"`   // The limit order
	SecondaryID ids.ID      `json:"secondaryId"` // The stop order
	Symbol      string      `json:"symbol"`
	Owner       ids.ShortID `json:"owner"`
	Status      string      `json:"status"` // "active", "triggered", "cancelled"
}

OCOOrder represents a One-Cancels-Other order pair

type Order

type Order struct {
	ID          ids.ID      `json:"id"`
	Owner       ids.ShortID `json:"owner"`
	Symbol      string      `json:"symbol"`
	Side        Side        `json:"side"`
	Type        OrderType   `json:"type"`
	Price       uint64      `json:"price"`     // Price in quote asset (scaled by 1e18)
	Quantity    uint64      `json:"quantity"`  // Quantity in base asset (scaled by 1e18)
	FilledQty   uint64      `json:"filledQty"` // Already filled quantity
	StopPrice   uint64      `json:"stopPrice"` // For stop orders
	Status      OrderStatus `json:"status"`
	CreatedAt   int64       `json:"createdAt"`   // Unix timestamp in nanoseconds
	ExpiresAt   int64       `json:"expiresAt"`   // Unix timestamp in nanoseconds
	PostOnly    bool        `json:"postOnly"`    // Only add liquidity
	ReduceOnly  bool        `json:"reduceOnly"`  // Only reduce position
	TimeInForce string      `json:"timeInForce"` // GTC, IOC, FOK
}

Order represents a trading order in the orderbook.

func (*Order) IsActive

func (o *Order) IsActive() bool

IsActive returns true if the order can still be filled.

func (*Order) RemainingQuantity

func (o *Order) RemainingQuantity() uint64

RemainingQuantity returns the unfilled quantity.

type OrderStatus

type OrderStatus uint8

OrderStatus represents the status of an order.

const (
	StatusOpen OrderStatus = iota
	StatusPartiallyFilled
	StatusFilled
	StatusCancelled
	StatusExpired
)

func (OrderStatus) String

func (s OrderStatus) String() string

type OrderType

type OrderType uint8

OrderType represents the type of order.

const (
	Limit OrderType = iota
	Market
	StopLoss
	TakeProfit
	StopLimit
)
const (
	Iceberg   OrderType = 10 // Iceberg order - partially hidden
	Hidden    OrderType = 11 // Fully hidden order
	Peg       OrderType = 12 // Pegged to best bid/ask
	Bracket   OrderType = 13 // Trailing stop order
	PostOnly  OrderType = 14 // Post-only order (explicit type)
	ReduceOnl OrderType = 15 // Reduce-only order (explicit type)
)

Additional order types for advanced trading

func (OrderType) String

func (t OrderType) String() string

type Orderbook

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

Orderbook maintains the bid and ask sides for a trading pair.

func New

func New(symbol string) *Orderbook

New creates a new orderbook for the given symbol.

func (*Orderbook) AddOrder

func (ob *Orderbook) AddOrder(order *Order) ([]*Trade, error)

AddOrder adds a new order to the orderbook. Returns executed trades if the order is matched.

func (*Orderbook) CancelOrder

func (ob *Orderbook) CancelOrder(orderID ids.ID) error

CancelOrder cancels an order by ID.

func (*Orderbook) GetBestAsk

func (ob *Orderbook) GetBestAsk() uint64

GetBestAsk returns the best (lowest) ask price.

func (*Orderbook) GetBestBid

func (ob *Orderbook) GetBestBid() uint64

GetBestBid returns the best (highest) bid price.

func (*Orderbook) GetDepth

func (ob *Orderbook) GetDepth(maxLevels int) (bids, asks []*PriceLevel)

GetDepth returns the orderbook depth up to maxLevels.

func (*Orderbook) GetMidPrice

func (ob *Orderbook) GetMidPrice() uint64

GetMidPrice returns the mid-market price.

func (*Orderbook) GetOrder

func (ob *Orderbook) GetOrder(orderID ids.ID) (*Order, error)

GetOrder returns an order by ID.

func (*Orderbook) GetSpread

func (ob *Orderbook) GetSpread() uint64

GetSpread returns the bid-ask spread.

func (*Orderbook) GetStats

func (ob *Orderbook) GetStats() (totalVolume, tradeCount uint64, lastTradeTime int64)

GetStats returns orderbook statistics.

func (*Orderbook) Match

func (ob *Orderbook) Match() []Trade

Match runs the matching engine and returns all trades from crossed orders. This is called per-block for deterministic matching. It processes all resting orders that can cross with each other.

func (*Orderbook) Symbol

func (ob *Orderbook) Symbol() string

Symbol returns the trading pair symbol.

type PeggedOrder added in v1.22.76

type PeggedOrder struct {
	*Order

	// PegType: "primary" (same side), "market" (opposite), "mid" (midpoint)
	PegType string `json:"pegType"`

	// PegOffset is the distance from the peg price (in price units)
	// Positive = more aggressive, Negative = less aggressive
	PegOffset int64 `json:"pegOffset"`

	// LastPegPrice tracks the last calculated peg price
	LastPegPrice uint64 `json:"lastPegPrice"`
}

PeggedOrder represents an order pegged to the best bid/ask

func NewPeggedOrder added in v1.22.76

func NewPeggedOrder(order *Order, pegType string, pegOffset int64) (*PeggedOrder, error)

NewPeggedOrder creates a new pegged order

func (*PeggedOrder) CalculatePegPrice added in v1.22.76

func (po *PeggedOrder) CalculatePegPrice(bestBid, bestAsk uint64) uint64

CalculatePegPrice determines the pegged price based on current market

type PriceLevel

type PriceLevel struct {
	Price    uint64   `json:"price"`
	Quantity uint64   `json:"quantity"`
	Orders   []*Order `json:"-"` // Orders at this level
}

PriceLevel represents a price level in the orderbook with aggregated quantity.

type Side

type Side uint8

Side represents the order side (buy or sell).

const (
	Buy Side = iota
	Sell
)

func (Side) String

func (s Side) String() string

type StopEngine added in v1.22.76

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

StopEngine manages stop orders and triggers them based on price movements

func NewStopEngine added in v1.22.76

func NewStopEngine() *StopEngine

NewStopEngine creates a new stop order engine

func (*StopEngine) AddStopOrder added in v1.22.76

func (se *StopEngine) AddStopOrder(order *Order, triggerType TriggerType, limitPrice uint64) error

AddStopOrder adds a stop order to the engine

func (*StopEngine) CheckStops added in v1.22.76

func (se *StopEngine) CheckStops(symbol string, price uint64) []*StopOrder

CheckStops checks all stops against a single price (simpler version)

func (*StopEngine) ClearTriggered added in v1.22.76

func (se *StopEngine) ClearTriggered() int

ClearTriggered removes all triggered stop orders

func (*StopEngine) GetNextTriggerPrice added in v1.22.76

func (se *StopEngine) GetNextTriggerPrice(symbol string, currentPrice uint64) (uint64, Side, bool)

GetNextTriggerPrice returns the next stop price that would trigger Returns (price, side, exists)

func (*StopEngine) GetPendingStops added in v1.22.76

func (se *StopEngine) GetPendingStops(symbol string) []*StopOrder

GetPendingStops returns all non-triggered stops for a symbol

func (*StopEngine) GetStats added in v1.22.76

func (se *StopEngine) GetStats() (totalStops, pendingStops, triggeredStops int)

GetStats returns engine statistics

func (*StopEngine) GetStopOrder added in v1.22.76

func (se *StopEngine) GetStopOrder(orderID ids.ID) (*StopOrder, error)

GetStopOrder returns a stop order by ID

func (*StopEngine) GetStopsBySymbol added in v1.22.76

func (se *StopEngine) GetStopsBySymbol(symbol string) []*StopOrder

GetStopsBySymbol returns all stop orders for a symbol

func (*StopEngine) RemoveStopOrder added in v1.22.76

func (se *StopEngine) RemoveStopOrder(orderID ids.ID) error

RemoveStopOrder removes a stop order from the engine

func (*StopEngine) SetTriggerCallback added in v1.22.76

func (se *StopEngine) SetTriggerCallback(callback func(order *StopOrder))

SetTriggerCallback sets the callback for when stops are triggered

func (*StopEngine) UpdatePrice added in v1.22.76

func (se *StopEngine) UpdatePrice(symbol string, lastPrice, markPrice, indexPrice uint64) []*StopOrder

UpdatePrice updates the price and triggers any stops

type StopOrder added in v1.22.76

type StopOrder struct {
	*Order

	// TriggerType defines the price type that triggers this stop
	TriggerType TriggerType `json:"triggerType"`

	// LimitPrice for stop-limit orders (0 = market order when triggered)
	LimitPrice uint64 `json:"limitPrice"`

	// TriggeredPrice is the price that caused the trigger
	TriggeredPrice uint64 `json:"triggeredPrice"`

	// Triggered indicates the stop has been activated
	Triggered bool `json:"triggered"`

	// TriggeredAt is the timestamp when triggered
	TriggeredAt int64 `json:"triggeredAt"`
}

StopOrder represents a stop order waiting to be triggered

func NewStopOrder added in v1.22.76

func NewStopOrder(order *Order, triggerType TriggerType, limitPrice uint64) (*StopOrder, error)

NewStopOrder creates a new stop order

func (*StopOrder) IsStopLimit added in v1.22.76

func (so *StopOrder) IsStopLimit() bool

IsStopLimit returns true if this is a stop-limit order

func (*StopOrder) ShouldTrigger added in v1.22.76

func (so *StopOrder) ShouldTrigger(price uint64) bool

ShouldTrigger checks if the stop should be triggered at the given price

type Trade

type Trade struct {
	ID          ids.ID      `json:"id"`
	Symbol      string      `json:"symbol"`
	MakerOrder  ids.ID      `json:"makerOrder"`
	TakerOrder  ids.ID      `json:"takerOrder"`
	Maker       ids.ShortID `json:"maker"`
	Taker       ids.ShortID `json:"taker"`
	Side        Side        `json:"side"`        // Taker's side
	Price       uint64      `json:"price"`       // Execution price
	Quantity    uint64      `json:"quantity"`    // Filled quantity
	MakerFee    uint64      `json:"makerFee"`    // Fee paid by maker
	TakerFee    uint64      `json:"takerFee"`    // Fee paid by taker
	Timestamp   int64       `json:"timestamp"`   // Execution timestamp
	BlockNumber uint64      `json:"blockNumber"` // Block where trade occurred
}

Trade represents a filled trade between two orders.

type TrailingStopOrder added in v1.22.76

type TrailingStopOrder struct {
	*Order

	// TrailAmount is the fixed trailing distance
	TrailAmount uint64 `json:"trailAmount"`

	// TrailPercent is the percentage trailing distance (basis points)
	TrailPercent uint64 `json:"trailPercent"`

	// HighWaterMark is the best price seen (for sell stops)
	HighWaterMark uint64 `json:"highWaterMark"`

	// LowWaterMark is the best price seen (for buy stops)
	LowWaterMark uint64 `json:"lowWaterMark"`

	// Activated indicates the stop has been triggered
	Activated bool `json:"activated"`
}

TrailingStopOrder represents a trailing stop order

func NewTrailingStopOrder added in v1.22.76

func NewTrailingStopOrder(order *Order, trailAmount, trailPercent uint64) (*TrailingStopOrder, error)

NewTrailingStopOrder creates a new trailing stop order

func (*TrailingStopOrder) ShouldTrigger added in v1.22.76

func (tso *TrailingStopOrder) ShouldTrigger(currentPrice uint64) bool

ShouldTrigger checks if the trailing stop should activate

func (*TrailingStopOrder) UpdateTrailingPrice added in v1.22.76

func (tso *TrailingStopOrder) UpdateTrailingPrice(currentPrice uint64) bool

UpdateTrailingPrice updates the stop price based on market movement

type TriggerType added in v1.22.76

type TriggerType uint8

TriggerType defines how the stop is triggered

const (
	TriggerOnLastPrice  TriggerType = iota // Last traded price
	TriggerOnMarkPrice                     // Mark price (index/oracle)
	TriggerOnIndexPrice                    // Index price only
)

Jump to

Keyboard shortcuts

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