Documentation
¶
Index ¶
- func AssertMemclobHasOrders(t *testing.T, ctx sdk.Context, memclob *MemClobPriceTimePriority, ...)
- func AssertMemclobHasShortTermTxBytes(t *testing.T, ctx sdk.Context, memclob *MemClobPriceTimePriority, ...)
- type MemClobPriceTimePriority
- func (m *MemClobPriceTimePriority) CancelOrder(ctx sdk.Context, msgCancelOrder *types.MsgCancelOrder) (offchainUpdates *types.OffchainUpdates, err error)
- func (m *MemClobPriceTimePriority) CreateOrderbook(clobPair types.ClobPair)
- func (m *MemClobPriceTimePriority) DeleverageSubaccount(ctx sdk.Context, subaccountId satypes.SubaccountId, perpetualId uint32, ...) (quantumsDeleveraged *big.Int, err error)
- func (m *MemClobPriceTimePriority) GenerateOffchainUpdatesForReplayPlaceOrder(ctx sdk.Context, err error, operation types.InternalOperation, ...) *types.OffchainUpdates
- func (m *MemClobPriceTimePriority) GenerateStreamOrderbookFill(ctx sdk.Context, clobMatch types.ClobMatch, takerOrder types.MatchableOrder, ...) types.StreamOrderbookFill
- func (m *MemClobPriceTimePriority) GenerateStreamTakerOrder(takerOrder types.MatchableOrder, takerOrderStatus types.TakerOrderStatus) types.StreamTakerOrder
- func (m *MemClobPriceTimePriority) GetCancelOrder(orderId types.OrderId) (tilBlock uint32, found bool)
- func (m *MemClobPriceTimePriority) GetMidPrice(ctx sdk.Context, clobPairId types.ClobPairId) (midPrice types.Subticks, bestBid types.Order, bestAsk types.Order, exists bool)
- func (m *MemClobPriceTimePriority) GetOffchainUpdatesForOrderbookSnapshot(ctx sdk.Context, clobPairId types.ClobPairId) (offchainUpdates *types.OffchainUpdates)
- func (m *MemClobPriceTimePriority) GetOperationsRaw(ctx sdk.Context) (operationsQueue []types.OperationRaw)
- func (m *MemClobPriceTimePriority) GetOperationsToReplay(ctx sdk.Context) ([]types.InternalOperation, map[types.OrderHash][]byte)
- func (m *MemClobPriceTimePriority) GetOrder(orderId types.OrderId) (order types.Order, found bool)
- func (m *MemClobPriceTimePriority) GetOrderFilledAmount(ctx sdk.Context, orderId types.OrderId) satypes.BaseQuantums
- func (m *MemClobPriceTimePriority) GetOrderRemainingAmount(ctx sdk.Context, order types.Order) (remainingAmount satypes.BaseQuantums, hasRemainingAmount bool)
- func (m *MemClobPriceTimePriority) GetOrderbookUpdatesForOrderPlacement(ctx sdk.Context, order types.Order) (offchainUpdates *types.OffchainUpdates)
- func (m *MemClobPriceTimePriority) GetOrderbookUpdatesForOrderRemoval(ctx sdk.Context, orderId types.OrderId) (offchainUpdates *types.OffchainUpdates)
- func (m *MemClobPriceTimePriority) GetOrderbookUpdatesForOrderUpdate(ctx sdk.Context, orderId types.OrderId) (offchainUpdates *types.OffchainUpdates)
- func (m *MemClobPriceTimePriority) GetPricePremium(ctx sdk.Context, clobPair types.ClobPair, ...) (premiumPpm int32, err error)
- func (m *MemClobPriceTimePriority) GetSubaccountOrders(clobPairId types.ClobPairId, subaccountId satypes.SubaccountId, ...) (openOrders []types.Order, err error)
- func (m *MemClobPriceTimePriority) InsertZeroFillDeleveragingIntoOperationsQueue(subaccountId satypes.SubaccountId, perpetualId uint32)
- func (m *MemClobPriceTimePriority) MaybeCreateOrderbook(clobPair types.ClobPair) (created bool)
- func (m *MemClobPriceTimePriority) PlaceOrder(ctx sdk.Context, order types.Order) (orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums, ...)
- func (m *MemClobPriceTimePriority) PlacePerpetualLiquidation(ctx sdk.Context, liquidationOrder types.LiquidationOrder) (orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums, ...)
- func (m *MemClobPriceTimePriority) PurgeInvalidMemclobState(ctx sdk.Context, filledOrderIds []types.OrderId, ...) *types.OffchainUpdates
- func (m *MemClobPriceTimePriority) RemoveAndClearOperationsQueue(ctx sdk.Context, localValidatorOperationsQueue []types.InternalOperation)
- func (m *MemClobPriceTimePriority) RemoveOrderIfFilled(ctx sdk.Context, orderId types.OrderId)
- func (m *MemClobPriceTimePriority) ReplayOperations(ctx sdk.Context, localOperations []types.InternalOperation, ...) *types.OffchainUpdates
- func (m *MemClobPriceTimePriority) SetClobKeeper(clobKeeper types.MemClobKeeper)
- func (m *MemClobPriceTimePriority) SetGenerateOrderbookUpdates(generateOrderbookUpdates bool)
- func (m *MemClobPriceTimePriority) SetMemclobGauges(ctx sdk.Context)
- type OrderWithRemainingSize
- type OrderWithRemovalReason
- type Orderbook
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AssertMemclobHasOrders ¶
func AssertMemclobHasOrders( t *testing.T, ctx sdk.Context, memclob *MemClobPriceTimePriority, expectedBids []OrderWithRemainingSize, expectedAsks []OrderWithRemainingSize, )
AssertMemclobHasOrders asserts that the memclob contains each passed in bid and ask order on the respective side and orderbook. It also verifies the expected state of each orderbook that holds at least one order, specifically the `BestBid` and `BestAsk`.
func AssertMemclobHasShortTermTxBytes ¶
func AssertMemclobHasShortTermTxBytes( t *testing.T, ctx sdk.Context, memclob *MemClobPriceTimePriority, expectedInternalOperations []types.InternalOperation, expectedRemainingBids []OrderWithRemainingSize, expectedRemainingAsks []OrderWithRemainingSize, )
AssertMemclobHasShortTermTxBytes asserts that the memclob contains a TX bytes entry for each Short-Term order on the orderbook and in the operations queue.
Types ¶
type MemClobPriceTimePriority ¶
type MemClobPriceTimePriority struct {
// contains filtered or unexported fields
}
func NewMemClobPriceTimePriority ¶
func NewMemClobPriceTimePriority( generateOffchainUpdates bool, ) *MemClobPriceTimePriority
func (*MemClobPriceTimePriority) CancelOrder ¶
func (m *MemClobPriceTimePriority) CancelOrder( ctx sdk.Context, msgCancelOrder *types.MsgCancelOrder, ) (offchainUpdates *types.OffchainUpdates, err error)
For short-term orders, CancelOrder adds (or updates) a cancel to the desired `goodTilBlock` in the memclob. If a cancel already exists for this order with a lower `goodTilBlock`, the cancel is updated to the new `goodTilBlock`.
For short-term cancels, an error will be returned if any of the following conditions are true: - A cancel already exists for this order with the same or greater `GoodTilBlock`.
If the order is removed from the orderbook, an off-chain update message will be generated.
func (*MemClobPriceTimePriority) CreateOrderbook ¶
func (m *MemClobPriceTimePriority) CreateOrderbook( clobPair types.ClobPair, )
CreateOrderbook is used for updating memclob internal data structures to mark an orderbook as created. This function will panic if `clobPairId` already exists in any of the memclob's internal data structures.
func (*MemClobPriceTimePriority) DeleverageSubaccount ¶
func (m *MemClobPriceTimePriority) DeleverageSubaccount( ctx sdk.Context, subaccountId satypes.SubaccountId, perpetualId uint32, deltaQuantums *big.Int, isFinalSettlement bool, ) ( quantumsDeleveraged *big.Int, err error, )
DeleverageSubaccount will deleverage a subaccount by finding perpetual positions that can be used to offset the offending subaccount. All position will be closed at the bankruptcy price of the subaccount that is being deleveraged.
func (*MemClobPriceTimePriority) GenerateOffchainUpdatesForReplayPlaceOrder ¶
func (m *MemClobPriceTimePriority) GenerateOffchainUpdatesForReplayPlaceOrder( ctx sdk.Context, err error, operation types.InternalOperation, order types.Order, orderStatus types.OrderStatus, placeOrderOffchainUpdates *types.OffchainUpdates, existingOffchainUpdates *types.OffchainUpdates, ) *types.OffchainUpdates
GenerateOffchainUpdatesForReplayPlaceOrder is a helper function intended to be used in ReplayOperations. It takes the results of a PlaceOrder function call, emits the according logs, and appends offchain updates for the replay operation to the existingOffchainUpdates object.
func (*MemClobPriceTimePriority) GenerateStreamOrderbookFill ¶
func (m *MemClobPriceTimePriority) GenerateStreamOrderbookFill( ctx sdk.Context, clobMatch types.ClobMatch, takerOrder types.MatchableOrder, makerOrders []types.Order, ) types.StreamOrderbookFill
GenerateStreamOrderbookFill wraps a clob match into the `StreamOrderbookFill` data structure which provides prices and fill amounts alongside clob match.
func (*MemClobPriceTimePriority) GenerateStreamTakerOrder ¶
func (m *MemClobPriceTimePriority) GenerateStreamTakerOrder( takerOrder types.MatchableOrder, takerOrderStatus types.TakerOrderStatus, ) types.StreamTakerOrder
GenerateStreamTakerOrder returns a `StreamTakerOrder` object used in full node streaming from a matchableOrder and a taker order status.
func (*MemClobPriceTimePriority) GetCancelOrder ¶
func (m *MemClobPriceTimePriority) GetCancelOrder( orderId types.OrderId, ) (tilBlock uint32, found bool)
GetCancelOrder returns the `tilBlock` expiry of an order cancelation and a bool indicating whether the expiry exists.
func (*MemClobPriceTimePriority) GetMidPrice ¶
func (m *MemClobPriceTimePriority) GetMidPrice( ctx sdk.Context, clobPairId types.ClobPairId, ) ( midPrice types.Subticks, bestBid types.Order, bestAsk types.Order, exists bool, )
GetMidPrice returns the mid price of the orderbook for the given clob pair and whether or not it exists. This function also returns the best bid and best ask orders, if they exist.
func (*MemClobPriceTimePriority) GetOffchainUpdatesForOrderbookSnapshot ¶
func (m *MemClobPriceTimePriority) GetOffchainUpdatesForOrderbookSnapshot( ctx sdk.Context, clobPairId types.ClobPairId, ) (offchainUpdates *types.OffchainUpdates)
GetOffchainUpdatesForOrderbookSnapshot returns the offchain updates for the orderbook snapshot. This is used by the gRPC streaming server to send the orderbook snapshot to the client.
func (*MemClobPriceTimePriority) GetOperationsRaw ¶
func (m *MemClobPriceTimePriority) GetOperationsRaw(ctx sdk.Context) ( operationsQueue []types.OperationRaw, )
GetOperationsRaw fetches the operations to propose in the next block in raw format for placement into MsgProposedOperations.
func (*MemClobPriceTimePriority) GetOperationsToReplay ¶
func (m *MemClobPriceTimePriority) GetOperationsToReplay(ctx sdk.Context) ( []types.InternalOperation, map[types.OrderHash][]byte, )
GetOperationsToReplay fetches the operations to replay in `PrepareCheckState`.
func (*MemClobPriceTimePriority) GetOrder ¶
func (m *MemClobPriceTimePriority) GetOrder( orderId types.OrderId, ) (order types.Order, found bool)
GetOrder gets an order by ID and returns it.
func (*MemClobPriceTimePriority) GetOrderFilledAmount ¶
func (m *MemClobPriceTimePriority) GetOrderFilledAmount( ctx sdk.Context, orderId types.OrderId, ) satypes.BaseQuantums
GetOrderFilledAmount returns the total filled amount of an order from state.
func (*MemClobPriceTimePriority) GetOrderRemainingAmount ¶
func (m *MemClobPriceTimePriority) GetOrderRemainingAmount( ctx sdk.Context, order types.Order, ) ( remainingAmount satypes.BaseQuantums, hasRemainingAmount bool, )
GetOrderRemainingAmount returns the remaining amount of an order (its size minus its filled amount). It also returns a boolean indicating whether the remaining amount is positive (true) or not (false).
func (*MemClobPriceTimePriority) GetOrderbookUpdatesForOrderPlacement ¶
func (m *MemClobPriceTimePriority) GetOrderbookUpdatesForOrderPlacement( ctx sdk.Context, order types.Order, ) (offchainUpdates *types.OffchainUpdates)
GetOrderbookUpdatesForOrderPlacement returns a place order offchain message and a update order offchain message used to add an order for the orderbook grpc stream.
func (*MemClobPriceTimePriority) GetOrderbookUpdatesForOrderRemoval ¶
func (m *MemClobPriceTimePriority) GetOrderbookUpdatesForOrderRemoval( ctx sdk.Context, orderId types.OrderId, ) (offchainUpdates *types.OffchainUpdates)
GetOrderbookUpdatesForOrderRemoval returns a remove order offchain message used to remove an order for the orderbook grpc stream.
func (*MemClobPriceTimePriority) GetOrderbookUpdatesForOrderUpdate ¶
func (m *MemClobPriceTimePriority) GetOrderbookUpdatesForOrderUpdate( ctx sdk.Context, orderId types.OrderId, ) (offchainUpdates *types.OffchainUpdates)
GetOrderbookUpdatesForOrderUpdate returns an update order offchain message used to update an order for the orderbook grpc stream.
func (*MemClobPriceTimePriority) GetPricePremium ¶
func (m *MemClobPriceTimePriority) GetPricePremium( ctx sdk.Context, clobPair types.ClobPair, params perptypes.GetPricePremiumParams, ) ( premiumPpm int32, err error, )
GetPricePremium calculates the premium for a perpetual market, using the equation `P = (Max(0, Impact Bid - Index Price) - Max(0, Index Price - Impact Ask)) / Index Price`. This is equivalent to the following piece-wise function:
If Index < Impact Bid: P = Impact Bid / Index - 1 If Impact Bid ≤ Index ≤ Impact Ask: P = 0 If Impact Ask < Index: P = Impact Ask / Index - 1
`Impact Bid/Ask Price` is the average price at which the impact bid/ask order (with size of `ImpactNotionalQuoteQuantums`) is filled. If `ImpactNotionalQuoteQuantums` is zero, the `Best Bid/Ask Price` is used as `Impact Price`. Note that this implies that if there's not enough liquidity for both ask and bid, 0 premium is returned since Impact Bid = `0` and Impact Ask = `infinity`.
func (*MemClobPriceTimePriority) GetSubaccountOrders ¶
func (m *MemClobPriceTimePriority) GetSubaccountOrders( clobPairId types.ClobPairId, subaccountId satypes.SubaccountId, side types.Order_Side, ) (openOrders []types.Order, err error)
GetSubaccountOrders gets all of a subaccount's order on a specific CLOB and side. This function will panic if `side` is invalid or if the orderbook does not exist.
func (*MemClobPriceTimePriority) InsertZeroFillDeleveragingIntoOperationsQueue ¶
func (m *MemClobPriceTimePriority) InsertZeroFillDeleveragingIntoOperationsQueue( subaccountId satypes.SubaccountId, perpetualId uint32, )
InsertZeroFillDeleveragingIntoOperationsQueue inserts a zero-fill deleveraging operation into the operations queue. This is used to signify that a subaccount has negative TNC and withdrawals should be disabled.
func (*MemClobPriceTimePriority) MaybeCreateOrderbook ¶
func (m *MemClobPriceTimePriority) MaybeCreateOrderbook( clobPair types.ClobPair, ) (created bool)
MaybeCreateOrderbook is used for updating memclob internal data structures to mark an orderbook as created.
func (*MemClobPriceTimePriority) PlaceOrder ¶
func (m *MemClobPriceTimePriority) PlaceOrder( ctx sdk.Context, order types.Order, ) ( orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums, orderStatus types.OrderStatus, offchainUpdates *types.OffchainUpdates, err error, )
PlaceOrder will perform the following operations: - Validate the order against memclob in-memory state. - If the newly placed order causes an overlap, match orders within that orderbook.
- Note that if any maker orders fail collateralization checks they will be removed, and if the taker order fails collateralization checks then matching will stop.
- If there were any matches resulting from matching the taker order, memclob state will be updated accordingly.
- If the order has nonzero remaining size after it has been matched and passes collateralization checks, the order will be added to the orderbook and other bookkeeping datastructures.
This function will return the amount of optimistically filled size (in base quantums) of the order that was filled while attempting to match the taker order against the book, along with the status of the placed order. If order validation failed, no state in the memclob will be modified and an error will be returned.
func (*MemClobPriceTimePriority) PlacePerpetualLiquidation ¶
func (m *MemClobPriceTimePriority) PlacePerpetualLiquidation( ctx sdk.Context, liquidationOrder types.LiquidationOrder, ) ( orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums, orderStatus types.OrderStatus, offchainUpdates *types.OffchainUpdates, err error, )
PlacePerpetualLiquidation matches an IOC liquidation order against the orderbook. Specifically, it will perform the following operations:
- If the liquidation order overlaps the orderbook, it will match orders within that orderbook until there is no overlap.
- Note that if any maker orders fail collateralization checks they will be removed, and it won't perform collateralization checks on the taker order.
- If there were any matches resulting from matching the liquidation order, memclob state will be updated accordingly.
func (*MemClobPriceTimePriority) PurgeInvalidMemclobState ¶
func (m *MemClobPriceTimePriority) PurgeInvalidMemclobState( ctx sdk.Context, filledOrderIds []types.OrderId, expiredStatefulOrderIds []types.OrderId, canceledStatefulOrderIds []types.OrderId, removedStatefulOrderIds []types.OrderId, existingOffchainUpdates *types.OffchainUpdates, ) *types.OffchainUpdates
PurgeInvalidMemclobState will purge the following invalid state from the memclob: - Expired Short-Term order cancellations. - Expired Short-Term and stateful orders. - Fully-filled orders. - Canceled stateful orders. - Forcefully removed stateful orders.
func (*MemClobPriceTimePriority) RemoveAndClearOperationsQueue ¶
func (m *MemClobPriceTimePriority) RemoveAndClearOperationsQueue( ctx sdk.Context, localValidatorOperationsQueue []types.InternalOperation, )
RemoveAndClearOperationsQueue is called during `Commit`/`PrepareCheckState` to clear and remove all orders that exist in the provided local validator's OTP (`operationsToPropose`). It performs the following steps: 1. Copy the operations queue. 2. Clear the OTP. Note that this also removes nonces for every operation in the OTP. 3. For each order placement operation in the copy, remove the order from the book if it exists.
func (*MemClobPriceTimePriority) RemoveOrderIfFilled ¶
func (m *MemClobPriceTimePriority) RemoveOrderIfFilled( ctx sdk.Context, orderId types.OrderId, )
RemoveOrderIfFilled removes an order from the orderbook if it currently fully filled in state.
func (*MemClobPriceTimePriority) ReplayOperations ¶
func (m *MemClobPriceTimePriority) ReplayOperations( ctx sdk.Context, localOperations []types.InternalOperation, shortTermOrderTxBytes map[types.OrderHash][]byte, existingOffchainUpdates *types.OffchainUpdates, postOnlyFilter bool, ) *types.OffchainUpdates
ReplayOperations will replay the provided operations onto the memclob. This is used to replay all local operations from the local `operationsToPropose` from the previous block. The following operations are supported: - Short-Term orders. - Newly-placed stateful orders. - Pre-existing stateful orders. - Stateful cancelations. Note that match operations are no-op.
Note that this function also takes in a postOnlyFilter variable and only places post-only orders if postOnlyFilter is true and non-post-only orders if postOnlyFilter is false.
func (*MemClobPriceTimePriority) SetClobKeeper ¶
func (m *MemClobPriceTimePriority) SetClobKeeper(clobKeeper types.MemClobKeeper)
SetClobKeeper sets the MemClobKeeper reference for this MemClob. This method is called after the MemClob struct is initialized. This reference is set with an explicit method call rather than during `NewMemClobPriceTimePriority` due to the bidirectional dependency between the Keeper and the MemClob.
func (*MemClobPriceTimePriority) SetGenerateOrderbookUpdates ¶
func (m *MemClobPriceTimePriority) SetGenerateOrderbookUpdates(generateOrderbookUpdates bool)
SetGenerateOffchainUpdates sets the `generateOffchainUpdates` field of the MemClob.
func (*MemClobPriceTimePriority) SetMemclobGauges ¶
func (m *MemClobPriceTimePriority) SetMemclobGauges( ctx sdk.Context, )
SetMemclobGauges sets gauges for each orderbook and the operations queue based on current memclob state. This is used only for observability purposes.
type OrderWithRemainingSize ¶
type OrderWithRemainingSize struct { Order types.Order RemainingSize satypes.BaseQuantums }
OrderWithRemainingSize is a testing utility struct used for storing an order along with the expected remaining size.
type OrderWithRemovalReason ¶
type OrderWithRemovalReason struct { Order types.Order RemovalReason types.OrderRemoval_RemovalReason }
type Orderbook ¶
type Orderbook struct { // Defines the tick size of the orderbook by defining how many subticks // are in one tick. That is, the subticks of any valid order must be a // multiple of this value. Generally this value should start `>= 100` to // allow room for decreasing it. This field is stored in state as part of a // `ClobPair`, but must be made available to the in-memory `Orderbook` in // order to efficiently remove orders from the orderbook. See the `removeOrder` // implementation for more information. SubticksPerTick types.SubticksPerTick // Map of price level (in subticks) to buy orders contained at that level. Bids map[types.Subticks]*types.Level // Map of price level (in subticks) to sell orders contained at that level. Asks map[types.Subticks]*types.Level // The highest bid on this orderbook, in subticks. 0 if no bids exist. BestBid types.Subticks // The lowest ask on this orderbook, in subticks. math.MaxUint64 if no asks exist. BestAsk types.Subticks // Contains all open orders on this CLOB for a given subaccount and side. // Used for fetching open orders for the add to orderbook collateralization // check for a subaccount. SubaccountOpenClobOrders map[satypes.SubaccountId]map[types.Order_Side]map[types.OrderId]bool // Minimum size of an order on the CLOB, in base quantums. MinOrderBaseQuantums satypes.BaseQuantums // Contains all open reduce-only orders on this CLOB from each subaccount. Used for tracking // which open reduce-only orders should be canceled when a position changes sides. SubaccountOpenReduceOnlyOrders map[satypes.SubaccountId]map[types.OrderId]bool // TotalOpenOrders tracks the total number of open orders in an orderbook for observability purposes. TotalOpenOrders uint // contains filtered or unexported fields }
Orderbook holds the bids and asks for a specific `ClobPairId`.
func (*Orderbook) GetMidPrice ¶
GetMidPrice returns the mid price of the orderbook and whether or not it exists.