memclob

package
v0.0.0-...-cc24d94 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2023 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

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) CountSubaccountShortTermOrders

func (m *MemClobPriceTimePriority) CountSubaccountShortTermOrders(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
) (count uint32)

CountSubaccountOrders will count the number of open short-term orders for a given subaccount.

Must be invoked with `CheckTx` context.

func (*MemClobPriceTimePriority) CreateOrderbook

func (m *MemClobPriceTimePriority) CreateOrderbook(
	ctx sdk.Context,
	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) GetCancelOrder

func (m *MemClobPriceTimePriority) GetCancelOrder(
	ctx sdk.Context,
	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) 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(
	ctx sdk.Context,
	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) 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(
	ctx sdk.Context,
	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) 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,
) *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.

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) 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
}

Jump to

Keyboard shortcuts

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