types: add order sorting by price

This commit is contained in:
c9s 2023-11-30 17:09:54 +08:00
parent 96f6f9e0d0
commit f21170aa5d
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 69 additions and 0 deletions

View File

@ -20,6 +20,24 @@ func SortOrdersAscending(orders []Order) []Order {
return orders
}
// SortOrdersByPrice sorts by creation time ascending-ly
func SortOrdersByPrice(orders []Order, descending bool) []Order {
var f func(i, j int) bool
if descending {
f = func(i, j int) bool {
return orders[i].Price.Compare(orders[j].Price) > 0
}
} else {
f = func(i, j int) bool {
return orders[i].Price.Compare(orders[j].Price) < 0
}
}
sort.Slice(orders, f)
return orders
}
// SortOrdersAscending sorts by update time ascending-ly
func SortOrdersUpdateTimeAscending(orders []Order) []Order {
sort.Slice(orders, func(i, j int) bool {

View File

@ -5,6 +5,8 @@ import (
"time"
"github.com/stretchr/testify/assert"
"github.com/c9s/bbgo/pkg/fixedpoint"
)
func TestSortTradesAscending(t *testing.T) {
@ -29,3 +31,52 @@ func TestSortTradesAscending(t *testing.T) {
trades = SortTradesAscending(trades)
assert.True(t, trades[0].Time.Before(trades[1].Time.Time()))
}
func getOrderPrices(orders []Order) (prices fixedpoint.Slice) {
for _, o := range orders {
prices = append(prices, o.Price)
}
return prices
}
func TestSortOrdersByPrice(t *testing.T) {
t.Run("ascending", func(t *testing.T) {
orders := []Order{
{SubmitOrder: SubmitOrder{Price: number("10.0")}},
{SubmitOrder: SubmitOrder{Price: number("30.0")}},
{SubmitOrder: SubmitOrder{Price: number("20.0")}},
{SubmitOrder: SubmitOrder{Price: number("25.0")}},
{SubmitOrder: SubmitOrder{Price: number("15.0")}},
}
orders = SortOrdersByPrice(orders, false)
prices := getOrderPrices(orders)
assert.Equal(t, fixedpoint.Slice{
number(10.0),
number(15.0),
number(20.0),
number(25.0),
number(30.0),
}, prices)
})
t.Run("descending", func(t *testing.T) {
orders := []Order{
{SubmitOrder: SubmitOrder{Price: number("10.0")}},
{SubmitOrder: SubmitOrder{Price: number("30.0")}},
{SubmitOrder: SubmitOrder{Price: number("20.0")}},
{SubmitOrder: SubmitOrder{Price: number("25.0")}},
{SubmitOrder: SubmitOrder{Price: number("15.0")}},
}
orders = SortOrdersByPrice(orders, true)
prices := getOrderPrices(orders)
assert.Equal(t, fixedpoint.Slice{
number(30.0),
number(25.0),
number(20.0),
number(15.0),
number(10.0),
}, prices)
})
}