protocol

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: GPL-3.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// OrderTypeUnknownUint8 represents an unknown order type in binary format.
	OrderTypeUnknownUint8 uint8 = 0
	// OrderTypeMarketUint8 represents a market order in binary format.
	OrderTypeMarketUint8 uint8 = 1
	// OrderTypeLimitUint8 represents a limit order in binary format.
	OrderTypeLimitUint8 uint8 = 2
	// OrderTypeFOKUint8 represents a Fill-Or-Kill order in binary format.
	OrderTypeFOKUint8 uint8 = 3
	// OrderTypeIOCUint8 represents an Immediate-Or-Cancel order in binary format.
	OrderTypeIOCUint8 uint8 = 4
	// OrderTypePostUint8 represents a post-only order in binary format.
	OrderTypePostUint8 uint8 = 5
	// OrderTypeCancelUint8 represents a cancellation request in binary format.
	OrderTypeCancelUint8 uint8 = 6
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AmendOrderCommand

type AmendOrderCommand struct {
	CommandID string `json:"-"`
	OrderID   string `json:"order_id"`
	UserID    uint64 `json:"user_id"`
	NewPrice  string `json:"new_price"`
	NewSize   string `json:"new_size"`
	Timestamp int64  `json:"timestamp"`
}

AmendOrderCommand is the payload for modifying an existing order.

func (*AmendOrderCommand) BinarySize

func (c *AmendOrderCommand) BinarySize() int

BinarySize returns the size of the command in binary format.

func (*AmendOrderCommand) MarshalBinary

func (c *AmendOrderCommand) MarshalBinary(buf []byte) (int, error)

MarshalBinary serializes the AmendOrderCommand to binary format.

func (*AmendOrderCommand) UnmarshalBinary

func (c *AmendOrderCommand) UnmarshalBinary(data []byte) (int, error)

UnmarshalBinary deserializes the AmendOrderCommand from binary format.

type CancelOrderCommand

type CancelOrderCommand struct {
	CommandID string `json:"-"`
	OrderID   string `json:"order_id"`
	UserID    uint64 `json:"user_id"`
	Timestamp int64  `json:"timestamp"`
}

CancelOrderCommand is the payload for canceling an existing order.

func (*CancelOrderCommand) BinarySize

func (c *CancelOrderCommand) BinarySize() int

BinarySize returns the size of the command in binary format.

func (*CancelOrderCommand) MarshalBinary

func (c *CancelOrderCommand) MarshalBinary(buf []byte) (int, error)

MarshalBinary serializes the CancelOrderCommand to binary format.

func (*CancelOrderCommand) UnmarshalBinary

func (c *CancelOrderCommand) UnmarshalBinary(data []byte) (int, error)

UnmarshalBinary deserializes the CancelOrderCommand from binary format.

type Command

type Command struct {
	// Version is the protocol version for backward compatibility.
	Version uint8 `json:"version"`

	// MarketID is the target market for this command (Routing Header).
	MarketID string `json:"market_id"`

	// SeqID is used for global ordering and deduplication.
	SeqID uint64 `json:"seq_id"`

	// Type identifies the payload type for fast routing.
	Type CommandType `json:"type"`

	// CommandID is the original identifier provided by the submitter.
	CommandID string `json:"command_id"`

	// Payload contains the serialized business data (e.g., JSON bytes of PlaceOrderCommand).
	// We use lazy deserialization to optimize routing performance.
	Payload []byte `json:"payload"`

	// Metadata stores non-business context (e.g., Tracing ID, Source IP).
	Metadata map[string]string `json:"metadata,omitempty"`
}

Command is the standard carrier for commands entering the Matching Engine. It is designed to be efficient for serialization and compatible with Event Sourcing.

type CommandType

type CommandType uint8

CommandType defines the type of the command (using uint8 for memory alignment and performance).

const (
	// CmdUnknown is the default unknown command.
	CmdUnknown CommandType = 0
	// CmdCreateMarket creates a new market.
	CmdCreateMarket CommandType = 1
	// CmdSuspendMarket suspends a market.
	CmdSuspendMarket CommandType = 2
	// CmdResumeMarket resumes a suspended market.
	CmdResumeMarket CommandType = 3
	// CmdUpdateConfig updates market configuration.
	CmdUpdateConfig CommandType = 4

	// CmdPlaceOrder places a new order.
	CmdPlaceOrder CommandType = 51
	// CmdCancelOrder cancels an existing order.
	CmdCancelOrder CommandType = 52
	// CmdAmendOrder modifies an existing order.
	CmdAmendOrder CommandType = 53
	// CmdUserEvent is a generic user event.
	CmdUserEvent CommandType = 100 // Generic User Event (e.g., EndOfBlock, Audit)
)

Command Type Numbering Strategy: - 0-50: OrderBook Management Commands (internal, low-frequency admin operations) - 51+: Trading Commands (external, high-frequency hot path).

type CreateMarketCommand

type CreateMarketCommand struct {
	UserID     uint64 `json:"user_id"`      // Operator ID for audit trail
	MarketID   string `json:"market_id"`    // Unique market identifier
	MinLotSize string `json:"min_lot_size"` // Minimum trade unit (e.g., "0.00000001")
	Timestamp  int64  `json:"timestamp"`
}

CreateMarketCommand is the payload for creating a new market/order book.

type DefaultJSONSerializer

type DefaultJSONSerializer struct{}

DefaultJSONSerializer is a high-performance JSON serializer using the sonic library.

func (*DefaultJSONSerializer) Marshal

func (s *DefaultJSONSerializer) Marshal(v any) ([]byte, error)

Marshal serializes the value to JSON.

func (*DefaultJSONSerializer) Unmarshal

func (s *DefaultJSONSerializer) Unmarshal(data []byte, v any) error

Unmarshal deserializes the JSON data into the value.

type DepthItem

type DepthItem struct {
	Price string `json:"price"`
	Size  string `json:"size"`
	Count int64  `json:"count"`
}

DepthItem represents a single price level in the order book depth.

type FastBinaryMarshaler

type FastBinaryMarshaler interface {
	MarshalBinary(buf []byte) (int, error)
	BinarySize() int
}

FastBinaryMarshaler is implemented by types that can serialize themselves into a binary format efficiently.

type FastBinarySerializer

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

FastBinarySerializer implements the Serializer interface, prioritizing manual binary serialization for supported types with a JSON fallback.

func (*FastBinarySerializer) Marshal

func (s *FastBinarySerializer) Marshal(v any) ([]byte, error)

Marshal serializes the value to binary format if supported, otherwise to JSON.

func (*FastBinarySerializer) Unmarshal

func (s *FastBinarySerializer) Unmarshal(data []byte, v any) error

Unmarshal deserializes the binary data if supported, otherwise from JSON.

type FastBinaryUnmarshaler

type FastBinaryUnmarshaler interface {
	UnmarshalBinary(data []byte) (int, error)
}

FastBinaryUnmarshaler is implemented by types that can deserialize themselves from a binary format efficiently.

type GetDepthRequest

type GetDepthRequest struct {
	MarketID string `json:"market_id"`
	Limit    uint32 `json:"limit"`
}

GetDepthRequest is the payload for querying order book depth. This is used for synchronous queries via gRPC/HTTP, separate from the async Command stream.

type GetDepthResponse

type GetDepthResponse struct {
	UpdateID uint64       `json:"update_id"`
	Asks     []*DepthItem `json:"asks"`
	Bids     []*DepthItem `json:"bids"`
}

GetDepthResponse represents the state of the order book depth.

type GetStatsRequest

type GetStatsRequest struct {
	MarketID string `json:"market_id"`
}

GetStatsRequest is the payload for querying order book statistics.

type GetStatsResponse

type GetStatsResponse struct {
	AskDepthCount int64 `json:"ask_depth_count"`
	AskOrderCount int64 `json:"ask_order_count"`
	BidDepthCount int64 `json:"bid_depth_count"`
	BidOrderCount int64 `json:"bid_order_count"`
}

GetStatsResponse contains statistics about the order book queues.

type LogType

type LogType string

LogType represents the type of event log.

const (
	// LogTypeOpen is generated when an order is opened.
	LogTypeOpen LogType = "open"
	// LogTypeMatch is generated when a trade match occurs.
	LogTypeMatch LogType = "match"
	// LogTypeCancel is generated when an order is canceled.
	LogTypeCancel LogType = "cancel"
	// LogTypeAmend is generated when an order is amended.
	LogTypeAmend LogType = "amend"
	// LogTypeReject is generated when an order or command is rejected.
	LogTypeReject LogType = "reject"
	// LogTypeUser is generated for generic user events.
	LogTypeUser LogType = "user_event"
	// LogTypeAdmin is generated for successful management commands.
	LogTypeAdmin LogType = "admin_event"
)

type OrderBookState

type OrderBookState uint8

OrderBookState represents the lifecycle state of an order book.

const (
	// OrderBookStateRunning indicates the order book is active and accepting all trading operations.
	OrderBookStateRunning OrderBookState = 0
	// OrderBookStateSuspended indicates the order book is temporarily paused; only cancel operations are allowed.
	OrderBookStateSuspended OrderBookState = 1
	// OrderBookStateHalted indicates the order book is permanently stopped; no operations are allowed.
	OrderBookStateHalted OrderBookState = 2
)

type OrderType

type OrderType string

OrderType represents the type of order.

const (
	// OrderTypeMarket represents a market order.
	OrderTypeMarket OrderType = "market"
	// OrderTypeLimit represents a limit order.
	OrderTypeLimit OrderType = "limit"
	// OrderTypeFOK represents a Fill-Or-Kill order.
	OrderTypeFOK OrderType = "fok" // Fill Or Kill
	// OrderTypeIOC represents an Immediate-Or-Cancel order.
	OrderTypeIOC OrderType = "ioc" // Immediate Or Cancel
	// OrderTypePostOnly represents a post-only (maker-only) order.
	OrderTypePostOnly OrderType = "post_only" // Maker only
	// OrderTypeCancel represents a cancellation request.
	OrderTypeCancel OrderType = "cancel" // The order has been canceled
)

func OrderTypeFromUint8

func OrderTypeFromUint8(v uint8) OrderType

OrderTypeFromUint8 converts the binary representation to an OrderType.

func (OrderType) ToUint8

func (ot OrderType) ToUint8() uint8

ToUint8 converts the OrderType to its binary representation.

type PlaceOrderCommand

type PlaceOrderCommand struct {
	CommandID   string    `json:"-"`
	OrderID     string    `json:"order_id"`
	Side        Side      `json:"side"`
	OrderType   OrderType `json:"order_type"`
	Price       string    `json:"price"` // Using string to prevent precision loss in JSON
	Size        string    `json:"size"`
	VisibleSize string    `json:"visible_size,omitempty"`
	QuoteSize   string    `json:"quote_size,omitempty"`
	UserID      uint64    `json:"user_id"`
	Timestamp   int64     `json:"timestamp"`
}

PlaceOrderCommand is the payload for placing a new order.

func (*PlaceOrderCommand) BinarySize

func (c *PlaceOrderCommand) BinarySize() int

BinarySize returns the size of the command in binary format.

func (*PlaceOrderCommand) MarshalBinary

func (c *PlaceOrderCommand) MarshalBinary(buf []byte) (int, error)

MarshalBinary serializes the PlaceOrderCommand to binary format.

func (*PlaceOrderCommand) UnmarshalBinary

func (c *PlaceOrderCommand) UnmarshalBinary(data []byte) (int, error)

UnmarshalBinary deserializes the PlaceOrderCommand from binary format.

type RejectReason

type RejectReason string

RejectReason represents the reason why an order was rejected.

const (
	// RejectReasonNone indicates no rejection.
	RejectReasonNone RejectReason = ""
	// RejectReasonNoLiquidity indicates no orders available to match.
	RejectReasonNoLiquidity RejectReason = "no_liquidity" // Market/IOC/FOK: No orders available to match
	// RejectReasonPriceMismatch indicates price does not meet requirements.
	RejectReasonPriceMismatch RejectReason = "price_mismatch" // IOC/FOK: Price does not meet requirements
	// RejectReasonInsufficientSize indicates order cannot be fully filled.
	RejectReasonInsufficientSize RejectReason = "insufficient_size" // FOK: Cannot be fully filled
	// RejectReasonPostOnlyMatch indicates PostOnly order would match immediately.
	RejectReasonPostOnlyMatch RejectReason = "post_only_match" // PostOnly: Would match immediately
	// RejectReasonDuplicateID indicates duplicate order ID.
	RejectReasonDuplicateID RejectReason = "duplicate_order_id"
	// RejectReasonOrderNotFound indicates order not found for cancel/amend.
	RejectReasonOrderNotFound RejectReason = "order_not_found"
	// RejectReasonInvalidPayload indicates invalid command payload.
	RejectReasonInvalidPayload RejectReason = "invalid_payload"

	// RejectReasonMarketNotFound is returned when the target market does not exist.
	RejectReasonMarketNotFound RejectReason = "market_not_found"
	// RejectReasonMarketAlreadyExists is returned when the market ID is already in use.
	RejectReasonMarketAlreadyExists RejectReason = "market_already_exists"
	// RejectReasonMarketSuspended is returned when the market is suspended.
	RejectReasonMarketSuspended RejectReason = "market_suspended"
	// RejectReasonMarketHalted is returned when the market is permanently halted.
	RejectReasonMarketHalted RejectReason = "market_halted"
	// RejectReasonUnauthorized is returned when the operator is not authorized.
	RejectReasonUnauthorized RejectReason = "unauthorized"
)

type ResumeMarketCommand

type ResumeMarketCommand struct {
	UserID    uint64 `json:"user_id"`   // Operator ID for audit trail
	MarketID  string `json:"market_id"` // Target market to resume
	Timestamp int64  `json:"timestamp"`
}

ResumeMarketCommand is the payload for resuming a suspended market.

type Serializer

type Serializer interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

Serializer defines the contract for serializing and deserializing command payloads.

type Side

type Side int8

Side represents the order side (Buy/Sell).

const (
	// SideBuy represents the buy side.
	SideBuy Side = 1
	// SideSell represents the sell side.
	SideSell Side = 2
)

type SuspendMarketCommand

type SuspendMarketCommand struct {
	UserID    uint64 `json:"user_id"`   // Operator ID for audit trail
	MarketID  string `json:"market_id"` // Target market to suspend
	Reason    string `json:"reason"`    // Reason for suspension (for audit)
	Timestamp int64  `json:"timestamp"`
}

SuspendMarketCommand is the payload for suspending a market.

type UpdateConfigCommand

type UpdateConfigCommand struct {
	UserID     uint64 `json:"user_id"`                // Operator ID for audit trail
	MarketID   string `json:"market_id"`              // Target market
	MinLotSize string `json:"min_lot_size,omitempty"` // New minimum lot size (optional)
	Timestamp  int64  `json:"timestamp"`
}

UpdateConfigCommand is the payload for updating market configuration.

type UserEventCommand

type UserEventCommand struct {
	CommandID string `json:"-"`
	UserID    uint64 `json:"user_id"`    // Operator ID for audit trail
	EventType string `json:"event_type"` // e.g. "EndOfBlock", "AdminMarker"
	Key       string `json:"key,omitempty"`
	Data      []byte `json:"data,omitempty"`
	Timestamp int64  `json:"timestamp"`
}

UserEventCommand is the payload for generic user events.

Jump to

Keyboard shortcuts

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