func shouldInsertBefore(kind OrderKind, order1Price sdk.Coin, order2Price sdk.Coin) bool {
	if kind == BuyOrder {
		if !order2Price.IsGTE(order1Price) {
			return true
		}
		return false
	}
	if !order1Price.IsGTE(order2Price) {
		return true
	}
	return false
}
In a buy orderbook, highest prices come first, in a sell orderbook, lowest come first.
package exchange
import (
	"fmt"
	sdk "github.com/cosmos/cosmos-sdk/types"
)
type OrderBook struct {
	Key         []byte       `json:"key"`
	Kind        OrderKind    `json:"kind"`
	AmountDenom string       `json:"amountDenom"`
	PriceDenom  string       `json:"priceDenom"`
	Orders      []LimitOrder `json:"orders"`
}
var orderBookSubspace = []byte("orderBook:")
func NewOrderBook(kind OrderKind, amountDenom string, priceDenom string) OrderBook {
	newOrderBook := OrderBook{
		Key:         MakeKeyOrderBook(kind, amountDenom, priceDenom),
		Kind:        kind,
		AmountDenom: amountDenom,
		PriceDenom:  priceDenom,
		Orders:      []LimitOrder{},  
	}
	return newOrderBook
}
func MakeKeyOrderBook(kind OrderKind, amountDenom string, priceDenom string) []byte {
	return []byte(fmt.Sprintf("orderBook:%v:%v:%v", kind, amountDenom, priceDenom))
}
func (ob *OrderBook) String() string {
	return fmt.Sprintf("OrderBook{Key: %v, Kind: %v, AmountDenom: %v, PriceDenom: %v, Orders: %v}",
		ob.Key, ob.Kind, ob.AmountDenom, ob.PriceDenom, ob.Orders)
}
func (ob *OrderBook) AddLimitOrder(limitOrder LimitOrder) sdk.Error {
	if ob.AmountDenom != limitOrder.Amount.Denom {
		return sdk.ErrInternal(
			fmt.Sprintf("Amount denom does not match between limit order %v and order book %v", limitOrder, ob))
	}
	if ob.PriceDenom != limitOrder.Price.Denom {
		return sdk.ErrInternal(
			fmt.Sprintf("Price denom does not match between limit order %v and order book %v", limitOrder, ob))
	}
	if ob.Kind != limitOrder.Kind {
		return sdk.ErrInternal(
			fmt.Sprintf("Kind does not match between limit order %v and order book %v", limitOrder, ob))
	}
	if len(ob.Orders) == 0 {
		ob.Orders = []LimitOrder{limitOrder}
		return nil
	}
	newOrders := make([]LimitOrder, len(ob.Orders)+1)
	added := false
	for i, order := range ob.Orders {
		if added {
			newOrders[i+1] = order
			continue
		}
		if shouldInsertBefore(ob.Kind, limitOrder.Price, order.Price) {
			newOrders[i] = limitOrder
			added = true
			newOrders[i+1] = order
		} else {
			newOrders[i] = order
		}
	}
	if !added {
		newOrders[len(ob.Orders)] = limitOrder
	}
	ob.Orders = newOrders
	return nil
}
func (ob *OrderBook) RemoveFilledLimitOrders() {
	newOrders := make([]LimitOrder, 0, len(ob.Orders))
	for _, order := range ob.Orders {
		if order.Amount.IsZero() {
			continue
		}
		newOrders = append(newOrders, order)
	}
	ob.Orders = newOrders
}