matching

package
v0.3.8 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// UintPrecision is precision of decimal places for Uint.
	UintPrecision = 1_000_000_000_000
	// UintComma is the amount of zeros in UintPrecision.
	UintComma = 12
)

Variables

View Source
var (
	ErrOrderBookDuplicate        = errors.New("order book is duplicated")
	ErrOrderBookNotFound         = errors.New("order book is not found")
	ErrOrderDuplicate            = errors.New("order is duplicated")
	ErrOrderNotFound             = errors.New("order is not found")
	ErrPriceLevelDuplicate       = errors.New("price level is duplicated")
	ErrPriceLevelNotFound        = errors.New("price level is not found")
	ErrInvalidSymbol             = errors.New("invalid symbol")
	ErrInvalidOrderID            = errors.New("invalid order id")
	ErrInvalidOrderSide          = errors.New("invalid order side")
	ErrInvalidOrderDirection     = errors.New("invalid order direction")
	ErrInvalidOrderType          = errors.New("invalid order type")
	ErrInvalidOrderPrice         = errors.New("invalid order price")
	ErrInvalidOrderStopPrice     = errors.New("invalid order stop price")
	ErrInvalidOrderQuantity      = errors.New("invalid order quantity")
	ErrInvalidOrderQuoteQuantity = errors.New("invalid order quote quantity")
	ErrInvalidMarketSlippage     = errors.New("invalid market slippage")
	ErrForbiddenManualExecution  = errors.New("manual execution is forbidden for automatically matching engine")
	ErrOrderTreeNotFound         = errors.New("order tree not found")
	ErrNotEnoughLockedAmount     = errors.New("not enough locked amount for order")

	// OCO
	ErrBuyOCOStopPriceLessThanMarketPrice     = errors.New("stop price must be greater than market price (buy OCO order)")
	ErrBuyOCOLimitPriceGreaterThanMarketPrice = errors.New("limit order price must be less than market price (buy OCO order)")
	ErrSellOCOStopPriceGreaterThanMarketPrice = errors.New("stop price must be less than market price (sell OCO order)")
	ErrSellOCOLimitPriceLessThanMarketPrice   = errors.New("limit order price must be greater than market price (sell OCO order)")
	ErrOCOStopLimitNotZeroLocked              = errors.New("stop limit order locked must be zero: locked amount must be in limit order")

	// TPSL
	ErrBuySLStopPriceLessThanEnginePrice     = errors.New("stop price must be greater than engine price (buy stop-loss order)")
	ErrBuyTPStopPriceGreaterThanEnginePrice  = errors.New("stop price must be less than engine price (buy take-profit order)")
	ErrSellSLStopPriceGreaterThanEnginePrice = errors.New("stop price must be less than engine price (sell stop-loss order)")
	ErrSellTPStopPriceLessThanEnginePrice    = errors.New("stop price must be greater than engine price (sell take-profit order)")
	ErrSLNotZeroLocked                       = errors.New("stop limit order locked must be zero: locked amount must be in take profit")

	// Internal Errors
	ErrInternalExecutingOrderNotExecuted = errors.New("internal matching error: executing order not executed")
)

Errors used by the package.

Functions

func CheckLockedOCO added in v0.3.0

func CheckLockedOCO(stopLimit *Order, limit *Order) error

CheckLockedOCO calculates and validates available for OCO orders pair

func CheckLockedTPSL added in v0.3.0

func CheckLockedTPSL(tp *Order, sl *Order) error

CheckLockedTPSL calculates and validates available for TP/SL orders pair

func CheckLockedTPSLMarket added in v0.3.1

func CheckLockedTPSLMarket(tp *Order, sl *Order) error

CheckLockedTPSL calculates and validates available for market TP/SL orders pair. Only in quote mode

Types

type Allocator

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

Allocator is an object encapsulating all used objects allocation using sync.Pool internally.

func NewAllocator

func NewAllocator(usePool bool) *Allocator

NewAllocator creates and returns new Allocator instance.

func (*Allocator) GetOrder

func (a *Allocator) GetOrder() *Order

GetOrder allocates Order instance.

func (*Allocator) GetPriceLevel

func (a *Allocator) GetPriceLevel() *PriceLevelL3

GetPriceLevel allocates PriceLevelL3 instance.

func (*Allocator) NewPriceLevelReversedTree added in v0.3.3

func (a *Allocator) NewPriceLevelReversedTree() avl.Tree[Uint, *PriceLevelL3]

NewPriceLevelReversedTree releases PriceLevelTree instance in reversed order.

func (*Allocator) NewPriceLevelTree added in v0.3.3

func (a *Allocator) NewPriceLevelTree() avl.Tree[Uint, *PriceLevelL3]

NewPriceLevelTree allocates PriceLevelTree instance in direct order.

func (*Allocator) PutOrder

func (a *Allocator) PutOrder(order *Order)

PutOrder releases Order instance.

func (*Allocator) PutPriceLevel

func (a *Allocator) PutPriceLevel(priceLevel *PriceLevelL3)

PutPriceLevel releases PriceLevelL3 instance.

type Engine

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

Engine is used to manage the market with orders, price levels and order books. Automatic orders matching can be enabled with EnableMatching() method or can be manually performed with Match() method. NOTE: The matching engine is thread safe only when created with multithread flag.

func NewEngine

func NewEngine(handler Handler, multithread bool) *Engine

NewEngine creates and returns new Engine instance.

func (*Engine) AddOrder

func (e *Engine) AddOrder(order Order) error

AddOrder adds new order to the engine.

func (*Engine) AddOrderBook

func (e *Engine) AddOrderBook(symbol Symbol, marketPrice Uint, spModesConfig StopPriceModeConfig) (orderBook *OrderBook, err error)

AddOrderBook creates new order book and adds it to the engine.

func (*Engine) AddOrdersPair added in v0.1.1

func (e *Engine) AddOrdersPair(stopLimitOrder Order, limitOrder Order) error

AddOrdersPair adds new orders pair (OCO orders) to the engine. First order should be stop-limit order and second one should be limit order. NOTE: lock all amount in limit order.

func (*Engine) AddTPSL added in v0.2.0

func (e *Engine) AddTPSL(tp Order, sl Order) error

AddTPSL adds new orders pair take-profit and stop-loss (OCO orders) to the engine. The first order should be take-profit order and the second order should be stop-loss. Based on stop-limit type. NOTE: lock all amount in take-profit order.

func (*Engine) AddTPSLMarket added in v0.3.1

func (e *Engine) AddTPSLMarket(tp Order, sl Order) error

AddTPSLMarket adds new orders pair take-profit and stop-limit (OCO orders) to the engine. The first order should be take-profit order and the second order should be stop-limit. Based on stop type. NOTE: lock all amount in take-profit order.

func (*Engine) DeleteOrder

func (e *Engine) DeleteOrder(symbolID uint32, orderID uint64) error

DeleteOrder deletes the order from the engine.

func (*Engine) DeleteOrderBook

func (e *Engine) DeleteOrderBook(id uint32) (orderBook *OrderBook, err error)

DeleteOrderBook deletes order book from the engine.

func (*Engine) DisableMatching

func (e *Engine) DisableMatching()

DisableMatching disables automatic matching.

func (*Engine) EnableMatching

func (e *Engine) EnableMatching()

EnableMatching enables automatic matching.

func (*Engine) ExecuteOrder

func (e *Engine) ExecuteOrder(symbolID uint32, orderID uint64, quantity Uint) error

ExecuteOrder executes the order by the given quantity.

func (*Engine) ExecuteOrderByPrice

func (e *Engine) ExecuteOrderByPrice(symbolID uint32, orderID uint64, price Uint, quantity Uint) error

ExecuteOrderByPrice executes the order by the given price and quantity.

func (*Engine) GetMarketPriceForOrderBook added in v0.1.2

func (e *Engine) GetMarketPriceForOrderBook(symbolID uint32) (Uint, error)

GetMarketPriceForOrderBook return market price of given symbolID (last executed trade). NOTE: not concurrency safe, use when there is no matching process.

func (*Engine) IsMatchingEnabled

func (e *Engine) IsMatchingEnabled() bool

IsMatchingEnabled returns true if automatic matching is enabled.

func (*Engine) Match

func (e *Engine) Match()

Match matches crossed orders in all order books. Method will match all crossed orders in each order book. Buy orders will be matched with sell orders at arbitrage price starting from the top of the book. Matched orders will be executed with deleted form the order book. After the matching operation each order book will have the top (best) bid price guarantied less than the top (best) ask price!

func (*Engine) MitigateOrder

func (e *Engine) MitigateOrder(symbolID uint32, orderID uint64, newPrice Uint, newQuantity Uint, additionalAmountToLock Uint) error

MitigateOrder mitigates the order with the given new price and quantity.

func (*Engine) ModifyOrder

func (e *Engine) ModifyOrder(symbolID uint32, orderID uint64, newPrice Uint, newQuantity Uint) error

ModifyOrder modifies the order with the given new price and quantity.

func (*Engine) OrderBook

func (e *Engine) OrderBook(id uint32) *OrderBook

OrderBook returns the order book with given symbol id.

func (*Engine) OrderBooks

func (e *Engine) OrderBooks() int

OrderBooks returns total amount of currently existing order books.

func (*Engine) Orders

func (e *Engine) Orders() int

Orders returns total amount of currently existing orders.

func (*Engine) ReduceOrder

func (e *Engine) ReduceOrder(symbolID uint32, orderID uint64, quantity Uint) error

ReduceOrder reduces the order by the given quantity.

func (*Engine) ReplaceOrder

func (e *Engine) ReplaceOrder(symbolID uint32, orderID uint64, newID uint64, newPrice Uint, newQuantity Uint) error

ReplaceOrder replaces the order with a new one.

func (*Engine) SetIndexMarkPricesForOrderBook added in v0.3.1

func (e *Engine) SetIndexMarkPricesForOrderBook(symbolID uint32, indexPrice Uint, markPrice Uint, iterate bool) error

SetIndexMarkPricesForOrderBook sets index and prices for order book at the same time, it has ability to provoke matching iteration for disabled matching.

func (*Engine) SetIndexPriceForOrderBook added in v0.2.0

func (e *Engine) SetIndexPriceForOrderBook(symbolID uint32, price Uint, iterate bool) error

SetIndexPriceForOrderBook sets the index price for order book, it has ability to provoke matching iteration for disabled matching.

func (*Engine) SetMarkPriceForOrderBook added in v0.2.0

func (e *Engine) SetMarkPriceForOrderBook(symbolID uint32, price Uint, iterate bool) error

SetMarkPrice sets the mark price for order book, it has ability to provoke matching iteration for disabled matching.

func (*Engine) Start

func (e *Engine) Start()

Start starts the matching engine.

func (*Engine) Stop

func (e *Engine) Stop(forced bool)

Stop stops the matching engine. It releases all internally used order books and cleans whole order book state.

type Handler

type Handler interface {

	// Order book handlers
	OnAddOrderBook(orderBook *OrderBook)
	OnUpdateOrderBook(orderBook *OrderBook)
	OnDeleteOrderBook(orderBook *OrderBook)

	// Price level handlers
	OnAddPriceLevel(orderBook *OrderBook, update PriceLevelUpdate)
	OnUpdatePriceLevel(orderBook *OrderBook, update PriceLevelUpdate)
	OnDeletePriceLevel(orderBook *OrderBook, update PriceLevelUpdate)

	// Orders handlers
	OnAddOrder(orderBook *OrderBook, order *Order)
	OnActivateOrder(orderBook *OrderBook, order *Order)
	OnUpdateOrder(orderBook *OrderBook, order *Order)
	OnDeleteOrder(orderBook *OrderBook, order *Order)

	// Matching handlers
	OnExecuteOrder(orderBook *OrderBook, orderID uint64, price Uint, quantity Uint, quoteQuantity Uint)
	OnExecuteTrade(orderBook *OrderBook, makerOrderUpdate OrderUpdate, takerOrderUpdate OrderUpdate, price Uint, quantity Uint, quoteQuantity Uint)

	// Errors handler
	OnError(orderBook *OrderBook, err error)
}

type Limits added in v0.1.4

type Limits struct {
	Min  Uint
	Max  Uint
	Step Uint
}

Limits contains just 3 numbers (min, max and step) and used for price and lot size limitations.

func GetSoftLimits added in v0.3.0

func GetSoftLimits() Limits

func QuoteLotSizeLimits added in v0.3.0

func QuoteLotSizeLimits(priceLimits Limits, lotSizeLimits Limits) Limits

func (Limits) Valid added in v0.3.0

func (l Limits) Valid() bool

type Order

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

Order contains information about an order. An order is an instruction to buy or sell on a trading venue such as a stock market, bond market, commodity market, or financial derivative market. These instructions can be simple or complicated, and can be sent to either a broker or directly to a trading venue via direct market access.

func NewLimitOrder

func NewLimitOrder(
	symbolID uint32,
	orderID uint64,
	side OrderSide,
	direction OrderDirection,
	timeInForce OrderTimeInForce,
	price Uint,
	quantity Uint,
	maxVisible Uint,
	restLocked Uint,
) Order

NewLimitOrder creates new limit order.

func NewMarketOrder

func NewMarketOrder(
	symbolID uint32,
	orderID uint64,
	side OrderSide,
	direction OrderDirection,
	timeInForce OrderTimeInForce,
	quantity Uint,
	quoteQuantity Uint,
	slippage Uint,
	restLocked Uint,
) Order

NewMarketOrder creates new market order.

func NewStopLimitOrder

func NewStopLimitOrder(
	symbolID uint32,
	orderID uint64,
	side OrderSide,
	direction OrderDirection,
	timeInForce OrderTimeInForce,
	price Uint,
	stopPriceMode StopPriceMode,
	stopPrice Uint,
	quantity Uint,
	maxVisible Uint,
	restLocked Uint,
) Order

NewStopLimitOrder creates new stop limit order.

func NewStopOrder

func NewStopOrder(
	symbolID uint32,
	orderID uint64,
	side OrderSide,
	direction OrderDirection,
	timeInForce OrderTimeInForce,
	stopPriceMode StopPriceMode,
	stopPrice Uint,
	quantity Uint,
	quoteQuantity Uint,
	slippage Uint,
	restLocked Uint,
) Order

NewStopOrder creates new stop order.

func NewTrailingStopLimitOrder

func NewTrailingStopLimitOrder(
	symbolID uint32,
	orderID uint64,
	side OrderSide,
	direction OrderDirection,
	timeInForce OrderTimeInForce,
	price Uint,
	stopPriceMode StopPriceMode,
	stopPrice Uint,
	quantity Uint,
	maxVisible Uint,
	trailingDistance Uint,
	trailingStep Uint,
	restLocked Uint,
) Order

NewTrailingStopLimitOrder creates new stop limit order.

func NewTrailingStopOrder

func NewTrailingStopOrder(
	symbolID uint32,
	orderID uint64,
	side OrderSide,
	direction OrderDirection,
	timeInForce OrderTimeInForce,
	stopPriceMode StopPriceMode,
	stopPrice Uint,
	quantity Uint,
	quoteQuantity Uint,
	slippage Uint,
	trailingDistance Uint,
	trailingStep Uint,
	restLocked Uint,
) Order

NewTrailingStopOrder creates new stop order.

func (*Order) Activated added in v0.2.0

func (o *Order) Activated() bool

func (*Order) AddAvailable added in v0.3.0

func (o *Order) AddAvailable(v Uint)

func (*Order) AddExecutedQuantity added in v0.3.0

func (o *Order) AddExecutedQuantity(v Uint)

func (*Order) AddExecutedQuoteQuantity added in v0.3.0

func (o *Order) AddExecutedQuoteQuantity(v Uint)

func (*Order) Available

func (o *Order) Available() Uint

Available returns order available amount equivalents to rest user locked amount of asset.

func (*Order) CheckLocked added in v0.3.0

func (o *Order) CheckLocked() error

CheckLocked checks locked quantity, all combinations of orders need exact minimum locked amount, except Buy Market Base, Sell Market Quote.

func (*Order) Clean added in v0.3.0

func (o *Order) Clean()

Clean cleans the order, use before put order to the pool

func (*Order) Debug added in v0.3.0

func (o *Order) Debug()

Debugging printer

func (*Order) Direction added in v0.3.2

func (o *Order) Direction() OrderDirection

Direction returns the market direction of the order.

func (*Order) ExecutedQuantity

func (o *Order) ExecutedQuantity() Uint

ExecutedQuantity returns order executed base quantity.

func (*Order) ExecutedQuoteQuantity

func (o *Order) ExecutedQuoteQuantity() Uint

ExecutedQuoteQuantity returns order executed quote quantity.

func (*Order) HiddenQuantity

func (o *Order) HiddenQuantity() Uint

HiddenQuantity returns order remaining hidden quantity.

func (*Order) ID

func (o *Order) ID() uint64

ID returns the order ID.

func (*Order) IsBuy

func (o *Order) IsBuy() bool

IsBuy returns true if buy order.

func (*Order) IsEndByPrice added in v0.3.7

func (o *Order) IsEndByPrice(priceOfLevel Uint) bool

func (*Order) IsExecuted

func (o *Order) IsExecuted() bool

IsExecuted returns true if the order is completely executed. It covers cases - when restQuantity is zero - when restQuoteQuantity (marketQuoteMode) - when check after deleting (cleaned order)

func (*Order) IsFOK

func (o *Order) IsFOK() bool

IsFOK returns true if 'Fill-Or-Kill' order.

func (*Order) IsGTC

func (o *Order) IsGTC() bool

IsGTC returns true if 'Good-Till-Cancelled' order.

func (*Order) IsHidden

func (o *Order) IsHidden() bool

IsHidden returns true if 'hidden' order.

func (*Order) IsIOC

func (o *Order) IsIOC() bool

IsIOC returns true if 'Immediate-Or-Cancel' order.

func (*Order) IsIceberg

func (o *Order) IsIceberg() bool

Iceberg returns true if 'iceberg' order.

func (*Order) IsLimit

func (o *Order) IsLimit() bool

IsLimit returns true if limit order.

func (*Order) IsLockingBase added in v0.3.2

func (o *Order) IsLockingBase() bool

func (*Order) IsLockingQuote added in v0.3.2

func (o *Order) IsLockingQuote() bool

func (*Order) IsMarket

func (o *Order) IsMarket() bool

IsMarket returns true if market order.

func (*Order) IsMarketSlippage

func (o *Order) IsMarketSlippage() bool

IsMarketSlippage returns true if slippage is specified for the market order.

func (*Order) IsSell

func (o *Order) IsSell() bool

IsSell returns true if sell order.

func (*Order) IsStop

func (o *Order) IsStop() bool

IsStop returns true if stop order.

func (*Order) IsStopLimit

func (o *Order) IsStopLimit() bool

IsStopLimit returns true if stop-limit order.

func (*Order) IsTakeProfit added in v0.1.1

func (o *Order) IsTakeProfit() bool

IsTrailingStop returns true if trailing stop order.

func (*Order) IsTrailingStop

func (o *Order) IsTrailingStop() bool

IsTrailingStop returns true if trailing stop order.

func (*Order) IsTrailingStopLimit

func (o *Order) IsTrailingStopLimit() bool

IsTrailingStopLimit returns true if trailing stop-limit order.

func (*Order) IsVirtualOB added in v0.3.1

func (o *Order) IsVirtualOB() bool

IsVirtualOB shows if the order uses virtual order book

func (*Order) LinkedOrderID added in v0.1.1

func (o *Order) LinkedOrderID() uint64

Linked order in OCO order pair (used for OCO orders only)

func (*Order) MarketSlippage

func (o *Order) MarketSlippage() Uint

MarketSlippage returns the slippage specified for the market order.

func (*Order) MaxVisibleQuantity

func (o *Order) MaxVisibleQuantity() Uint

MaxVisibleQuantity returns maximum visible in an order book quantity of the order.

func (*Order) PartiallyExecuted added in v0.2.0

func (o *Order) PartiallyExecuted() bool

func (*Order) Price

func (o *Order) Price() Uint

Price returns the order price.

func (*Order) Quantity

func (o *Order) Quantity() Uint

Quantity returns the order quantity.

func (*Order) QuoteQuantity

func (o *Order) QuoteQuantity() Uint

QuoteQuantity returns optional quote quantity of the market order.

func (*Order) RestQuantity

func (o *Order) RestQuantity() Uint

RestQuantity returns order remaining quantity.

func (*Order) RestQuoteQuantity added in v0.3.0

func (o *Order) RestQuoteQuantity() Uint

RestQuoteQuantity returns remaining quote quantity. Must be used only for market quote mode.

func (*Order) RestoreExecution

func (o *Order) RestoreExecution(executed, executedQuote, restQuantity Uint)

func (*Order) Side

func (o *Order) Side() OrderSide

Side returns the market side of the order.

func (*Order) StopPrice

func (o *Order) StopPrice() Uint

StopPrice returns the order stop price.

func (*Order) StopPriceMode added in v0.2.0

func (o *Order) StopPriceMode() StopPriceMode

StopPriceMode returns the order stop price mode.

func (*Order) SubAvailable added in v0.3.0

func (o *Order) SubAvailable(v Uint)

func (*Order) SubRestQuantity added in v0.3.0

func (o *Order) SubRestQuantity(v Uint)

func (*Order) SubRestQuoteQuantity added in v0.3.0

func (o *Order) SubRestQuoteQuantity(v Uint)

func (*Order) SymbolID

func (o *Order) SymbolID() uint32

SymbolID returns the symbol ID of the order.

func (*Order) TimeInForce

func (o *Order) TimeInForce() OrderTimeInForce

TimeInForce returns the time in force option of the order.

func (*Order) Type

func (o *Order) Type() OrderType

Type returns the order type.

func (*Order) Validate

func (o *Order) Validate(ob *OrderBook) error

Validate returns error if the order fails to pass validation so can be used safely.

func (*Order) VisibleQuantity

func (o *Order) VisibleQuantity() Uint

VisibleQuantity returns order remaining visible quantity.

type OrderBook

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

Order book is used to store buy and sell orders in a price level order. NOTE: Not thread-safe.

func NewOrderBook

func NewOrderBook(symbol Symbol, spModesConfig StopPriceModeConfig, taskQueueSize int) *OrderBook

NewOrderBook creates and returns new OrderBook instance.

func (*OrderBook) Clean

func (ob *OrderBook) Clean()

Clean releases all internally used tree nodes and cleans whole order book state.

func (*OrderBook) Debug added in v0.3.0

func (ob *OrderBook) Debug()

Debugging printer

func (*OrderBook) GetAsk

func (ob *OrderBook) GetAsk(price Uint) *avl.Node[Uint, *PriceLevelL3]

GetAsk returns sell order price level with given price.

func (*OrderBook) GetBid

func (ob *OrderBook) GetBid(price Uint) *avl.Node[Uint, *PriceLevelL3]

GetBid returns buy order price level with given price.

func (*OrderBook) GetBuyStop

func (ob *OrderBook) GetBuyStop(price Uint) *avl.Node[Uint, *PriceLevelL3]

GetBuyStop returns buy stop order price level with given price.

func (*OrderBook) GetIndexPrice added in v0.2.0

func (ob *OrderBook) GetIndexPrice() Uint

func (*OrderBook) GetMarkPrice added in v0.2.0

func (ob *OrderBook) GetMarkPrice() Uint

func (*OrderBook) GetMarketPrice added in v0.1.1

func (ob *OrderBook) GetMarketPrice() Uint

func (*OrderBook) GetMarketTrailingStopPriceAsk

func (ob *OrderBook) GetMarketTrailingStopPriceAsk() Uint

func (*OrderBook) GetMarketTrailingStopPriceBid

func (ob *OrderBook) GetMarketTrailingStopPriceBid() Uint

TODO: check later trailing prices

func (*OrderBook) GetSellStop

func (ob *OrderBook) GetSellStop(price Uint) *avl.Node[Uint, *PriceLevelL3]

GetSellStop returns sell stop order price level with given price.

func (*OrderBook) GetStopPrice added in v0.2.0

func (ob *OrderBook) GetStopPrice(m StopPriceMode) Uint

GetStopPrice is internal helper for matching.

func (*OrderBook) GetTrailingBuyStop

func (ob *OrderBook) GetTrailingBuyStop(price Uint) *avl.Node[Uint, *PriceLevelL3]

GetTrailingBuyStop returns trailing buy stop order price level with given price.

func (*OrderBook) GetTrailingSellStop

func (ob *OrderBook) GetTrailingSellStop(price Uint) *avl.Node[Uint, *PriceLevelL3]

GetTrailingSellStop returns trailing sell stop order price level with given price.

func (*OrderBook) IsEmpty

func (ob *OrderBook) IsEmpty() bool

IsEmpty returns true of the order book has no any orders.

func (*OrderBook) Order

func (ob *OrderBook) Order(id uint64) *Order

Order returns order with given id.

func (*OrderBook) Size

func (ob *OrderBook) Size() int

Size returns total amount of orders in the order book.

func (*OrderBook) Symbol

func (ob *OrderBook) Symbol() Symbol

Symbol returns order book symbol.

func (*OrderBook) TopAsk

func (ob *OrderBook) TopAsk() *avl.Node[Uint, *PriceLevelL3]

TopAsk returns best sell order price level.

func (*OrderBook) TopBid

func (ob *OrderBook) TopBid() *avl.Node[Uint, *PriceLevelL3]

TopBid returns best buy order price level.

func (*OrderBook) TopBuyStop

func (ob *OrderBook) TopBuyStop() *avl.Node[Uint, *PriceLevelL3]

TopBuyStop returns best buy stop order price level.

func (*OrderBook) TopSellStop

func (ob *OrderBook) TopSellStop() *avl.Node[Uint, *PriceLevelL3]

TopSellStop returns best sell stop order price level.

func (*OrderBook) TopTrailingBuyStop

func (ob *OrderBook) TopTrailingBuyStop() *avl.Node[Uint, *PriceLevelL3]

TopTrailingBuyStop returns best trailing buy stop order price level.

func (*OrderBook) TopTrailingSellStop

func (ob *OrderBook) TopTrailingSellStop() *avl.Node[Uint, *PriceLevelL3]

TopTrailingSellStop returns best trailing sell stop order price level.

func (*OrderBook) UpdateSymbol added in v0.1.6

func (ob *OrderBook) UpdateSymbol(sym Symbol) error

type OrderDirection added in v0.3.2

type OrderDirection uint8

Order direction show if order will close or open position. For spot trading sell is always closing position. For futures order it can be defined by user.

const (
	OrderDirectionOpen OrderDirection = iota + 1
	OrderDirectionClose
)

func (OrderDirection) String added in v0.3.2

func (od OrderDirection) String() string

type OrderSide

type OrderSide uint8

OrderSide is an enumeration of possible trading sides (buy/sell).

const (
	// OrderSideBuy represents market side which includes only buy orders (bids).
	OrderSideBuy OrderSide = iota + 1
	// OrderSideSell represents market side which includes only sell orders (asks).
	OrderSideSell
)

func (OrderSide) String added in v0.1.5

func (os OrderSide) String() string

type OrderTimeInForce

type OrderTimeInForce uint8

OrderTimeInForce is an enumeration of possible order execution options.

const (
	// Good-Till-Cancelled (GTC) - A GTC order is an order to buy or sell a stock that
	// lasts until the order is completed or cancelled.
	OrderTimeInForceGTC OrderTimeInForce = iota + 1
	// Immediate-Or-Cancel (IOC) - An IOC order is an order to buy or sell a stock that
	// must be executed immediately. Any portion of the order that cannot be filled immediately
	// will be cancelled.
	OrderTimeInForceIOC
	// Fill-Or-Kill (FOK) - An FOK order is an order to buy or sell a stock that must
	// be executed immediately in its entirety; otherwise, the entire order will be cancelled
	// (i.e., no partial execution of the order is allowed).
	OrderTimeInForceFOK
)

func (OrderTimeInForce) String added in v0.1.5

func (ot OrderTimeInForce) String() string

type OrderType

type OrderType uint8

OrderType is an enumeration of possible order types.

const (
	// A limit order is an order to buy or sell a stock at a specific
	// price or better. A buy limit order can only be executed at the limit price or lower,
	// and a sell limit order can only be executed at the limit price or higher. A limit
	// order is not guaranteed to execute. A limit order can only be filled if the stock's
	// market price reaches the limit price. While limit orders do not guarantee execution,
	// they help ensure that an investor does not pay more than a predetermined price for a
	// stock.
	OrderTypeLimit OrderType = iota + 1

	// A market order is an order to buy or sell a stock at the best
	// available price. Generally, this type of order will be executed immediately. However,
	// the price at which a market order will be executed is not guaranteed. It is important
	// for investors to remember that the last-traded price is not necessarily the price at
	// which a market order will be executed. In fast-moving markets, the price at which a
	// market order will execute often deviates from the last-traded price or "real time"
	// quote.
	OrderTypeMarket

	// A stop order, also referred to as a stop-loss order, is an order
	// to buy or sell a stock once the price of the stock reaches a specified price, known
	// as the stop price. When the stop price is reached, a stop order becomes a market order.
	// A buy stop order is entered at a stop price above the current market price. Investors
	// generally use a buy stop order to limit a loss or to protect a profit on a stock that
	// they have sold short. A sell stop order is entered at a stop price below the current
	// market price. Investors generally use a sell stop order to limit a loss or to protect
	// a profit on a stock that they own.
	OrderTypeStop

	// A stop-limit order is an order to buy or sell a stock that
	// combines the features of a stop order and a limit order. Once the stop price is reached,
	// a stop-limit order becomes a limit order that will be executed at a specified price (or
	// better). The benefit of a stop-limit order is that the investor can control the price at
	// which the order can be executed.
	OrderTypeStopLimit

	// A trailing stop order is entered with a stop parameter
	// that creates a moving or trailing activation price, hence the name. This parameter
	// is entered as a percentage change or actual specific amount of rise (or fall) in the
	// security price. Trailing stop sell orders are used to maximize and protect profit as
	// a stock's price rises and limit losses when its price falls.
	OrderTypeTrailingStop

	// A trailing stop-limit order is similar to a trailing stop order.
	// Instead of selling at market price when triggered, the order becomes a limit order.
	OrderTypeTrailingStopLimit
)

func (OrderType) String added in v0.1.5

func (ot OrderType) String() string

type OrderUpdate added in v0.3.0

type OrderUpdate struct {
	ID            uint64
	Quantity      Uint
	QuoteQuantity Uint
}

type PriceLevelL2

type PriceLevelL2 struct {
	Price  uint64
	Volume uint64
}

PriceLevelL2 contains price and visible volume in order bool.

type PriceLevelL3

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

PriceLevelL3 contains price and total/visible volume in order bool and encapsulates order queue management. Total volume is separated to visible and hidden parts (only total and visible values are stored for optimization). Internal queue structure is either pre-created circular queue in struct or circular queue in heap. By default pre-created queue in struct is used until orders amount increase it's capacity. NOTE: Not thread-safe.

func NewPriceLevelL3

func NewPriceLevelL3() *PriceLevelL3

NewPriceLevelL3 creates and returns new PriceLevelL3 instance.

func (*PriceLevelL3) Clean

func (pl *PriceLevelL3) Clean()

Clean cleans the price level by removing all queued orders.

func (*PriceLevelL3) Iterator added in v0.3.3

func (pl *PriceLevelL3) Iterator() list.Iterator[*Order]

func (*PriceLevelL3) Orders

func (pl *PriceLevelL3) Orders() int

Orders returns amount of orders in the queue.

func (*PriceLevelL3) Price

func (pl *PriceLevelL3) Price() Uint

Price returns price level of the queue.

func (*PriceLevelL3) Queue

func (pl *PriceLevelL3) Queue() *list.List[*Order]

Queue returns the order queue.

func (*PriceLevelL3) Visible

func (pl *PriceLevelL3) Visible() Uint

Visible returns visible orders volume.

func (*PriceLevelL3) Volume

func (pl *PriceLevelL3) Volume() Uint

Volume returns total orders volume.

type PriceLevelType

type PriceLevelType uint8

PriceLevelType is an enumeration of possible price level types (ask/bid).

const (
	// PriceLevelTypeBid represents bid price level type.
	PriceLevelTypeBid PriceLevelType = iota + 1
	// PriceLevelTypeAsk represents ask price level type.
	PriceLevelTypeAsk
)

func (PriceLevelType) String added in v0.1.5

func (plt PriceLevelType) String() string

type PriceLevelUpdate

type PriceLevelUpdate struct {
	ID      uint64
	Kind    PriceLevelUpdateKind
	Side    OrderSide
	Price   Uint // price of the price level
	Volume  Uint // total volume of the price level
	Visible Uint // visible volume of the price level
	Orders  int  // amount of orders queued in the price level
	Top     bool // top of the order book flag
}

PriceLevelUpdate contains complete info about a price level update.

type PriceLevelUpdateKind

type PriceLevelUpdateKind uint8

PriceLevelUpdateKind is an enumeration of possible price level update kinds (add, update, delete).

const (
	// PriceLevelUpdateKindAdd represents add price level update kind.
	PriceLevelUpdateKindAdd PriceLevelUpdateKind = iota + 1
	// PriceLevelUpdateKindUpdate represents update price level update kind.
	PriceLevelUpdateKindUpdate
	// PriceLevelUpdateKindDelete represents delete price level update kind.
	PriceLevelUpdateKindDelete
)

func (PriceLevelUpdateKind) String added in v0.1.5

func (uk PriceLevelUpdateKind) String() string

type StopPriceMode added in v0.2.0

type StopPriceMode uint8
const (
	StopPriceModeMarket StopPriceMode = iota + 1
	StopPriceModeMark
	StopPriceModeIndex
)

func (StopPriceMode) String added in v0.2.0

func (m StopPriceMode) String() string

type StopPriceModeConfig added in v0.2.0

type StopPriceModeConfig struct {
	Market bool
	Mark   bool
	Index  bool
}

func (StopPriceModeConfig) Modes added in v0.2.0

func (c StopPriceModeConfig) Modes() []StopPriceMode

type Symbol

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

Symbol contains basic info about a trading symbol.

func NewSymbol

func NewSymbol(id uint32, name string) Symbol

NewSymbol creates new symbol with specified ID and name.

func NewSymbolWithLimits added in v0.1.4

func NewSymbolWithLimits(id uint32, name string, priceLimits Limits, lotSizeLimits Limits) Symbol

NewSymbolWithLimits creates new symbol with specified ID, name, price and lot size limits.

func (Symbol) CalcQtyWithLimits added in v0.3.0

func (s Symbol) CalcQtyWithLimits(quoteQty, price Uint) Uint

func (Symbol) CalcQuoteQtyWithLimits added in v0.3.0

func (s Symbol) CalcQuoteQtyWithLimits(qty, price Uint) Uint

func (Symbol) ID

func (s Symbol) ID() uint32

ID returns the symbol ID.

func (Symbol) LotSizeLimits added in v0.1.4

func (s Symbol) LotSizeLimits() Limits

LotSizeLimits returns lot size limitations of the symbol.

func (Symbol) Name

func (s Symbol) Name() string

Name returns the symbol name.

func (Symbol) PriceLimits added in v0.1.4

func (s Symbol) PriceLimits() Limits

PriceLimits returns price limitations of the symbol.

func (Symbol) Valid added in v0.1.6

func (s Symbol) Valid() bool

type Uint

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

func ApplySteps added in v0.3.0

func ApplySteps(v Uint, step Uint) Uint

func Max

func Max(a Uint, b Uint) Uint

func Min

func Min(a Uint, b Uint) Uint

func NewMaxUint

func NewMaxUint() Uint

func NewUint

func NewUint(u uint64) Uint

func NewUintFromFloatString

func NewUintFromFloatString(number string) (Uint, error)

func NewUintFromStr

func NewUintFromStr(v string) (Uint, error)

func NewUintFromUint128

func NewUintFromUint128(u uint128.Uint128) Uint

func NewZeroUint

func NewZeroUint() Uint

func (Uint) Add

func (u Uint) Add(v Uint) Uint

func (Uint) Add64

func (u Uint) Add64(v uint64) Uint

func (Uint) Cmp

func (u Uint) Cmp(v Uint) int

func (Uint) Div64

func (u Uint) Div64(v uint64) Uint

func (Uint) Equals

func (u Uint) Equals(v Uint) bool

func (Uint) Equals64

func (u Uint) Equals64(v uint64) bool

func (Uint) GreaterThan

func (u Uint) GreaterThan(v Uint) bool

func (Uint) GreaterThanOrEqualTo

func (u Uint) GreaterThanOrEqualTo(v Uint) bool

func (Uint) IsMax

func (u Uint) IsMax() bool

func (Uint) IsZero

func (u Uint) IsZero() bool

func (Uint) LessThan

func (u Uint) LessThan(v Uint) bool

func (Uint) LessThanOrEqualTo

func (u Uint) LessThanOrEqualTo(v Uint) bool

func (Uint) Marshal

func (u Uint) Marshal() ([]byte, error)

func (Uint) MarshalJSON

func (u Uint) MarshalJSON() ([]byte, error)

func (Uint) MarshalTo

func (u Uint) MarshalTo(data []byte) (int, error)

func (Uint) Mul

func (u Uint) Mul(v Uint) Uint

func (Uint) Mul64

func (u Uint) Mul64(v uint64) Uint

func (Uint) QuoRem

func (u Uint) QuoRem(v Uint) (Uint, Uint)

func (Uint) Size

func (u Uint) Size() int

func (Uint) String

func (u Uint) String() string

func (Uint) Sub

func (u Uint) Sub(v Uint) Uint

func (Uint) ToFloatString

func (u Uint) ToFloatString() string

func (Uint) ToUint128

func (u Uint) ToUint128() uint128.Uint128

func (*Uint) Unmarshal

func (u *Uint) Unmarshal(data []byte) error

func (*Uint) UnmarshalJSON

func (u *Uint) UnmarshalJSON(data []byte) error

Directories

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

Jump to

Keyboard shortcuts

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