matching

package
v0.78.4-patch.1 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: AGPL-3.0 Imports: 21 Imported by: 0

README

Matching package

A trade matching engine matches up order bids and offers to generate trades. Matching engines allocate trades among competing bids and offers at the same price.

Calculating the cost of closing a trader out

This call will calculate the "cost" to the trader should the be closed out (based on current position). The actual position should be passed, along with a Side. If the trader holds a long position, the call should be:

closeOutPNL := matchingEngine.GetClosePNL(position.Size(), types.Side_Sell)

Internally, the matching engine will iterate over the order book (buy/sell side depending on the second argument). The "cheapest" orders will be used first. This means that, for the buy side, the price levels are traversed backwards (the levels are tracked in descending order). The sell side is stored in ascending order, and is traversed as-is.

This call has no effect on the order status (i.e. it won't change the Remaining field of the orders).

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotEnoughOrders signals that not enough orders were
	// in the book to achieve a given operation.
	ErrNotEnoughOrders   = errors.New("insufficient orders")
	ErrOrderDoesNotExist = errors.New("order does not exist")
	ErrInvalidVolume     = errors.New("invalid volume")
	ErrNoBestBid         = errors.New("no best bid")
	ErrNoBestAsk         = errors.New("no best ask")
	ErrNotCrossed        = errors.New("not crossed")
)
View Source
var (
	// ErrWashTrade signals an attempt to a wash trade from a party.
	ErrWashTrade    = errors.New("party attempted to submit wash trade")
	ErrFOKNotFilled = errors.New("FOK order could not be fully filled")
)
View Source
var ErrPriceNotFound = errors.New("price-volume pair not found")

ErrPriceNotFound signals that a price was not found on the book side.

View Source
var ErrUnknownPeggedOrderID = errors.New("unknow pegged order")

Functions

This section is empty.

Types

type BookCache

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

func NewBookCache

func NewBookCache() BookCache

func (*BookCache) GetIndicativePrice

func (c *BookCache) GetIndicativePrice() (*num.Uint, bool)

func (*BookCache) GetIndicativeUncrossingSide

func (c *BookCache) GetIndicativeUncrossingSide() (types.Side, bool)

func (*BookCache) GetIndicativeVolume

func (c *BookCache) GetIndicativeVolume() (uint64, bool)

func (*BookCache) Invalidate

func (c *BookCache) Invalidate()

func (*BookCache) SetIndicativePrice

func (c *BookCache) SetIndicativePrice(v *num.Uint)

func (*BookCache) SetIndicativeUncrossingSide

func (c *BookCache) SetIndicativeUncrossingSide(s types.Side)

func (*BookCache) SetIndicativeVolume

func (c *BookCache) SetIndicativeVolume(v uint64)

type CachedOrderBook

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

func NewCachedOrderBook

func NewCachedOrderBook(
	log *logging.Logger, config Config, market string, auction bool, peggedCounterNotify func(int64),
) *CachedOrderBook

func (*CachedOrderBook) AmendOrder

func (b *CachedOrderBook) AmendOrder(
	originalOrder, amendedOrder *types.Order,
) error

func (*CachedOrderBook) CancelAllOrders

func (b *CachedOrderBook) CancelAllOrders(
	party string,
) ([]*types.OrderCancellationConfirmation, error)

func (*CachedOrderBook) CancelOrder

func (*CachedOrderBook) DeleteOrder

func (b *CachedOrderBook) DeleteOrder(
	order *types.Order,
) (*types.Order, error)

func (*CachedOrderBook) EnterAuction

func (b *CachedOrderBook) EnterAuction() []*types.Order

func (*CachedOrderBook) GetIndicativePrice

func (b *CachedOrderBook) GetIndicativePrice() *num.Uint

func (*CachedOrderBook) GetIndicativePriceAndVolume

func (b *CachedOrderBook) GetIndicativePriceAndVolume() (*num.Uint, uint64, types.Side)

func (*CachedOrderBook) LeaveAuction

func (b *CachedOrderBook) LeaveAuction(
	at time.Time,
) ([]*types.OrderConfirmation, []*types.Order, error)

func (*CachedOrderBook) LoadState

func (b *CachedOrderBook) LoadState(ctx context.Context, payload *types.Payload) ([]types.StateProvider, error)

func (*CachedOrderBook) RemoveDistressedOrders

func (b *CachedOrderBook) RemoveDistressedOrders(
	parties []events.MarketPosition,
) ([]*types.Order, error)

func (*CachedOrderBook) RemoveOrder

func (b *CachedOrderBook) RemoveOrder(order string) (*types.Order, error)

func (*CachedOrderBook) ReplaceOrder

func (b *CachedOrderBook) ReplaceOrder(rm, rpl *types.Order) (*types.OrderConfirmation, error)

func (*CachedOrderBook) SetOffbookSource added in v0.77.0

func (b *CachedOrderBook) SetOffbookSource(obs OffbookSource)

func (*CachedOrderBook) SubmitOrder

func (b *CachedOrderBook) SubmitOrder(
	order *types.Order,
) (*types.OrderConfirmation, error)

func (*CachedOrderBook) UpdateAMM added in v0.77.0

func (b *CachedOrderBook) UpdateAMM(party string)

type Config

type Config struct {
	Level encoding.LogLevel `long:"log-level"`

	LogPriceLevelsDebug   bool `long:"log-price-levels-debug"`
	LogRemovedOrdersDebug bool `long:"log-removed-orders-debug"`
}

Config represents the configuration of the Matching engine.

func NewDefaultConfig

func NewDefaultConfig() Config

NewDefaultConfig creates an instance of the package specific configuration, given a pointer to a logger instance to be used for logging within the package.

type CumulativeVolumeLevel

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

CumulativeVolumeLevel represents the cumulative volume at a price level for both bid and ask.

type IndicativePriceAndVolume

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

func NewIndicativePriceAndVolume

func NewIndicativePriceAndVolume(log *logging.Logger, buy, sell *OrderBookSide) *IndicativePriceAndVolume

func (*IndicativePriceAndVolume) AddVolumeAtPrice

func (ipv *IndicativePriceAndVolume) AddVolumeAtPrice(price *num.Uint, volume uint64, side types.Side, isOffbook bool)

func (*IndicativePriceAndVolume) ExtractOffbookOrders added in v0.77.0

func (ipv *IndicativePriceAndVolume) ExtractOffbookOrders(price *num.Uint, side types.Side, target uint64) []*types.Order

ExtractOffbookOrders returns the cached expanded orders of AMM's in the crossed region of the given side. These are the order that we will send in aggressively to uncrossed the book.

func (*IndicativePriceAndVolume) GetCrossedRegion added in v0.77.0

func (ipv *IndicativePriceAndVolume) GetCrossedRegion() (*num.Uint, *num.Uint)

func (*IndicativePriceAndVolume) GetCumulativePriceLevels

func (ipv *IndicativePriceAndVolume) GetCumulativePriceLevels(maxPrice, minPrice *num.Uint) ([]CumulativeVolumeLevel, uint64)

func (*IndicativePriceAndVolume) RemoveVolumeAtPrice

func (ipv *IndicativePriceAndVolume) RemoveVolumeAtPrice(price *num.Uint, volume uint64, side types.Side, isOffbook bool)

type OffbookSource added in v0.77.0

type OffbookSource interface {
	BestPricesAndVolumes() (*num.Uint, uint64, *num.Uint, uint64)
	SubmitOrder(agg *types.Order, inner, outer *num.Uint) []*types.Order
	NotifyFinished()
	OrderbookShape(st, nd *num.Uint, id *string) ([]*types.Order, []*types.Order)
}

type OrderBook

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

OrderBook represents the book holding all orders in the system.

func NewOrderBook

func NewOrderBook(log *logging.Logger, config Config, marketID string, auction bool, peggedCountNotify func(int64)) *OrderBook

NewOrderBook create an order book with a given name.

func (*OrderBook) AmendOrder

func (b *OrderBook) AmendOrder(originalOrder, amendedOrder *types.Order) error

AmendOrder amends an order which is an active order on the book.

func (*OrderBook) BestBidPriceAndVolume

func (b *OrderBook) BestBidPriceAndVolume() (*num.Uint, uint64, error)

BestBidPriceAndVolume : Return the best bid and volume for the buy side of the book.

func (*OrderBook) BestOfferPriceAndVolume

func (b *OrderBook) BestOfferPriceAndVolume() (*num.Uint, uint64, error)

BestOfferPriceAndVolume : Return the best bid and volume for the sell side of the book.

func (*OrderBook) BidAndAskPresentAfterAuction

func (b *OrderBook) BidAndAskPresentAfterAuction() bool

func (*OrderBook) CanLeaveAuction

func (b *OrderBook) CanLeaveAuction() (withTrades, withoutTrades bool)

CanLeaveAuction calls canUncross with required trades and, if that returns false without required trades (which still permits leaving liquidity auction if canUncross with required trades returs true, both returns are true.

func (*OrderBook) CanUncross

func (b *OrderBook) CanUncross() bool

CanUncross - a clunky name for a somewhat clunky function: this checks if there will be LIMIT orders on the book after we uncross the book (at the end of an auction). If this returns false, the opening auction should be extended.

func (*OrderBook) CancelAllOrders

func (b *OrderBook) CancelAllOrders(party string) ([]*types.OrderCancellationConfirmation, error)

func (*OrderBook) CancelOrder

func (b *OrderBook) CancelOrder(order *types.Order) (*types.OrderCancellationConfirmation, error)

CancelOrder cancel an order that is active on an order book. Market and Order ID are validated, however the order must match the order on the book with respect to side etc. The caller will typically validate this by using a store, we should not trust that the external world can provide these values reliably.

func (*OrderBook) CheckBook added in v0.75.0

func (b *OrderBook) CheckBook() bool

func (*OrderBook) DeleteOrder

func (b *OrderBook) DeleteOrder(
	order *types.Order,
) (*types.Order, error)

DeleteOrder remove a given order on a given side from the book.

func (*OrderBook) EnterAuction

func (b *OrderBook) EnterAuction() []*types.Order

EnterAuction Moves the order book into an auction state.

func (*OrderBook) GetActivePeggedOrderIDs

func (b *OrderBook) GetActivePeggedOrderIDs() []string

GetActivePeggedOrderIDs returns the order identifiers of all pegged orders in the order book that are not parked.

func (*OrderBook) GetBestAskPrice

func (b *OrderBook) GetBestAskPrice() (*num.Uint, error)

func (*OrderBook) GetBestBidPrice

func (b *OrderBook) GetBestBidPrice() (*num.Uint, error)

func (*OrderBook) GetBestStaticAskPrice

func (b *OrderBook) GetBestStaticAskPrice() (*num.Uint, error)

func (*OrderBook) GetBestStaticAskPriceAndVolume

func (b *OrderBook) GetBestStaticAskPriceAndVolume() (*num.Uint, uint64, error)

func (*OrderBook) GetBestStaticBidPrice

func (b *OrderBook) GetBestStaticBidPrice() (*num.Uint, error)

func (*OrderBook) GetBestStaticBidPriceAndVolume

func (b *OrderBook) GetBestStaticBidPriceAndVolume() (*num.Uint, uint64, error)

func (*OrderBook) GetFillPrice added in v0.75.0

func (b *OrderBook) GetFillPrice(volume uint64, side types.Side) (*num.Uint, error)

GetFillPrice returns the average price which would be achieved for a given volume and give side of the book.

func (*OrderBook) GetIndicativePrice

func (b *OrderBook) GetIndicativePrice() (retprice *num.Uint)

GetIndicativePrice Calculates the indicative price of the order book without modifying the order book state.

func (*OrderBook) GetIndicativePriceAndVolume

func (b *OrderBook) GetIndicativePriceAndVolume() (retprice *num.Uint, retvol uint64, retside types.Side, offbookVolume uint64)

GetIndicativePriceAndVolume Calculates the indicative price and volume of the order book without modifying the order book state.

func (*OrderBook) GetIndicativeTrades

func (b *OrderBook) GetIndicativeTrades() ([]*types.Trade, error)

func (*OrderBook) GetLastTradedPrice added in v0.72.0

func (b *OrderBook) GetLastTradedPrice() *num.Uint

func (*OrderBook) GetOrderBookLevelCount added in v0.63.0

func (b *OrderBook) GetOrderBookLevelCount() uint64

GetOrderBookLevelCount returns the number of levels in the book.

func (*OrderBook) GetOrderByID

func (b *OrderBook) GetOrderByID(orderID string) (*types.Order, error)

GetOrderByID returns order by its ID (IDs are not expected to collide within same market).

func (*OrderBook) GetOrdersPerParty

func (b *OrderBook) GetOrdersPerParty(party string) []*types.Order

func (*OrderBook) GetPeggedOrdersCount added in v0.63.0

func (b *OrderBook) GetPeggedOrdersCount() uint64

func (*OrderBook) GetState

func (b *OrderBook) GetState(key string) ([]byte, []types.StateProvider, error)

func (*OrderBook) GetTotalNumberOfOrders

func (b *OrderBook) GetTotalNumberOfOrders() int64

GetTotalNumberOfOrders is a debug/testing function to return the total number of orders in the book.

func (*OrderBook) GetTotalVolume

func (b *OrderBook) GetTotalVolume() int64

GetTotalVolume is a debug/testing function to return the total volume in the order book.

func (*OrderBook) GetTrades

func (b *OrderBook) GetTrades(order *types.Order) ([]*types.Trade, error)

GetTrades returns the trades a given order generates if we were to submit it now this is used to calculate fees, perform price monitoring, etc...

func (*OrderBook) GetVolumeAtPrice added in v0.74.0

func (b *OrderBook) GetVolumeAtPrice(price *num.Uint, side types.Side) uint64

func (*OrderBook) Hash

func (b *OrderBook) Hash() []byte

func (OrderBook) InAuction

func (b OrderBook) InAuction() bool

func (*OrderBook) Keys

func (b *OrderBook) Keys() []string

func (*OrderBook) LeaveAuction

func (b *OrderBook) LeaveAuction(at time.Time) ([]*types.OrderConfirmation, []*types.Order, error)

LeaveAuction Moves the order book back into continuous trading state.

func (*OrderBook) LoadState

func (b *OrderBook) LoadState(_ context.Context, payload *types.Payload) ([]types.StateProvider, error)

func (OrderBook) Namespace

func (b OrderBook) Namespace() types.SnapshotNamespace

func (*OrderBook) PrintState

func (b *OrderBook) PrintState(types string)

PrintState prints the actual state of the book. this should be use only in debug / non production environment as it rely a lot on logging.

func (*OrderBook) ReSubmitSpecialOrders added in v0.62.0

func (b *OrderBook) ReSubmitSpecialOrders(order *types.Order)

func (*OrderBook) ReloadConf

func (b *OrderBook) ReloadConf(cfg Config)

ReloadConf is used in order to reload the internal configuration of the OrderBook.

func (*OrderBook) RemoveDistressedOrders

func (b *OrderBook) RemoveDistressedOrders(
	parties []events.MarketPosition,
) ([]*types.Order, error)

RemoveDistressedOrders remove from the book all order holding distressed positions.

func (*OrderBook) RemoveOrder

func (b *OrderBook) RemoveOrder(id string) (*types.Order, error)

RemoveOrder takes the order off the order book.

func (*OrderBook) ReplaceOrder

func (b *OrderBook) ReplaceOrder(rm, rpl *types.Order) (*types.OrderConfirmation, error)

func (*OrderBook) RestoreWithMarketPriceFactor added in v0.65.0

func (b *OrderBook) RestoreWithMarketPriceFactor(priceFactor num.Decimal)

RestoreWithMarketPriceFactor takes the given market price factor and updates all the OriginalPrices in the orders accordingly.

func (*OrderBook) SetOffbookSource added in v0.77.0

func (b *OrderBook) SetOffbookSource(obs OffbookSource)

func (*OrderBook) Settled

func (b *OrderBook) Settled() []*types.Order

func (*OrderBook) StopSnapshots

func (b *OrderBook) StopSnapshots()

func (*OrderBook) Stopped

func (b *OrderBook) Stopped() bool

func (*OrderBook) SubmitOrder

func (b *OrderBook) SubmitOrder(order *types.Order) (*types.OrderConfirmation, error)

SubmitOrder Add an order and attempt to uncross the book, returns a TradeSet protobuf message object.

func (*OrderBook) UpdateAMM added in v0.77.0

func (b *OrderBook) UpdateAMM(party string)

func (*OrderBook) VWAP added in v0.74.0

func (b *OrderBook) VWAP(volume uint64, side types.Side) (*num.Uint, error)

VWAP returns an error if the total volume for the side of the book is less than the given volume or if there are no levels. Otherwise it returns the volume weighted average price for achieving the given volume.

type OrderBookSide

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

OrderBookSide represent a side of the book, either Sell or Buy.

func (*OrderBookSide) BestPriceAndVolume

func (s *OrderBookSide) BestPriceAndVolume() (*num.Uint, uint64, error)

BestPriceAndVolume returns the top of book price and volume returns an error if the book is empty.

func (*OrderBookSide) BestStaticPrice

func (s *OrderBookSide) BestStaticPrice() (*num.Uint, error)

BestStaticPrice returns the top of book price for non pegged orders We do not keep count of the volume which makes this slightly quicker returns an error if the book is empty.

func (*OrderBookSide) BestStaticPriceAndVolume

func (s *OrderBookSide) BestStaticPriceAndVolume() (*num.Uint, uint64, error)

BestStaticPriceAndVolume returns the top of book price for non pegged orders returns an error if the book is empty.

func (*OrderBookSide) ExtractOrders

func (s *OrderBookSide) ExtractOrders(price *num.Uint, volume uint64, removeOrders bool) []*types.Order

ExtractOrders extracts the orders from the top of the book until the volume amount is hit, if removeOrders is set to True then the relevant orders also get removed.

func (*OrderBookSide) GetVolume

func (s *OrderBookSide) GetVolume(price *num.Uint) (uint64, error)

GetVolume returns the volume at the given pricelevel.

func (*OrderBookSide) Hash

func (s *OrderBookSide) Hash() []byte

func (*OrderBookSide) RemoveOrder

func (s *OrderBookSide) RemoveOrder(o *types.Order) (*types.Order, error)

RemoveOrder will remove an order from the book.

type PriceLevel

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

PriceLevel represents all the Orders placed at a given price.

func NewPriceLevel

func NewPriceLevel(price *num.Uint) *PriceLevel

NewPriceLevel instantiate a new PriceLevel.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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