mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-21 22:43:52 +00:00
types: add order sorting by price
This commit is contained in:
parent
96f6f9e0d0
commit
f21170aa5d
|
@ -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 {
|
||||
|
|
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user