Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Last active October 17, 2023 15:41
Show Gist options
  • Save Luke-Rogerson/0a52b1abe2bcb3770a8f1affdc72e637 to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/0a52b1abe2bcb3770a8f1affdc72e637 to your computer and use it in GitHub Desktop.
GetMinMaxPriceOrder, GetNextOrder
package redisrepo
import (
"context"
"github.com/google/uuid"
"github.com/orbs-network/order-book/models"
)
type OrderTraversal interface {
GetMinMaxPriceOrder(ctx context.Context, symbol models.Symbol, side models.Side) *models.Order
GetNextOrder(ctx context.Context, orderId uuid.UUID, symbol models.Symbol, side models.Side) *models.Order
}
func (r *redisRepository) GetMinMaxPriceOrder(ctx context.Context, symbol models.Symbol, side models.Side) (*models.Order, error) {
var key string
if side == models.BUY {
key = CreateBuySidePricesKey(symbol)
} else {
key = CreateSellSidePricesKey(symbol)
}
// get first element representing the min/max orderId
orderID, err := r.client.ZRange(ctx, key, 0, 0).Result()
if err != nil {
return nil, err
}
if len(orderID) == 0 {
return nil, models.ErrOrderNotFound
}
orderIdUUID, err := uuid.Parse(orderID[0])
if err != nil {
return nil, err
}
// get the order itself by id
order, err := r.FindOrderById(ctx, orderIdUUID)
if err != nil {
return nil, err
}
return order, nil
}
func (r *redisRepository) GetNextOrder(ctx context.Context, orderId uuid.UUID, symbol models.Symbol, side models.Side) (*models.Order, error) {
var key string
if side == models.BUY {
key = CreateBuySidePricesKey(symbol)
} else {
key = CreateSellSidePricesKey(symbol)
}
// get the current order's rank
rank, err := r.client.ZRank(ctx, key, orderId.String()).Result()
if err != nil {
return nil, err
}
// get the next order's id
nextOrderID, err := r.client.ZRange(ctx, key, rank+1, rank+1).Result()
if err != nil {
return nil, err
}
if len(nextOrderID) == 0 {
return nil, models.ErrOrderNotFound
}
nextOrderIdUUID, err := uuid.Parse(nextOrderID[0])
if err != nil {
return nil, err
}
// get the next order itself
nextOrder, err := r.FindOrderById(ctx, nextOrderIdUUID)
if err != nil {
return nil, err
}
return nextOrder, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment