From 6f81b0ee17e090221d44d530cd1abae8720f837e Mon Sep 17 00:00:00 2001 From: ycdesu Date: Tue, 2 Mar 2021 10:33:46 +0800 Subject: [PATCH] orderbook: fix IsValid logic The original implementation always returns an error. --- pkg/types/orderbook.go | 6 ++++- pkg/types/orderbook_test.go | 50 +++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 pkg/types/orderbook_test.go diff --git a/pkg/types/orderbook.go b/pkg/types/orderbook.go index 37ddd6f02..c96f72f97 100644 --- a/pkg/types/orderbook.go +++ b/pkg/types/orderbook.go @@ -154,7 +154,11 @@ func (b *OrderBook) IsValid() (bool, error) { return false, errors.New("empty asks") } - return bid.Price < ask.Price, fmt.Errorf("bid price %f > ask price %f", bid.Price.Float64(), ask.Price.Float64()) + if bid.Price > ask.Price { + return false, fmt.Errorf("bid price %f > ask price %f", bid.Price.Float64(), ask.Price.Float64()) + } + + return true, nil } func (b *OrderBook) PriceVolumesBySide(side SideType) PriceVolumeSlice { diff --git a/pkg/types/orderbook_test.go b/pkg/types/orderbook_test.go new file mode 100644 index 000000000..a342e82fa --- /dev/null +++ b/pkg/types/orderbook_test.go @@ -0,0 +1,50 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/c9s/bbgo/pkg/fixedpoint" +) + +func TestOrderBook_IsValid(t *testing.T) { + ob := OrderBook{ + Bids: PriceVolumeSlice{ + {fixedpoint.NewFromFloat(100.0), fixedpoint.NewFromFloat(1.5)}, + {fixedpoint.NewFromFloat(90.0), fixedpoint.NewFromFloat(2.5)}, + }, + + Asks: PriceVolumeSlice{ + {fixedpoint.NewFromFloat(110.0), fixedpoint.NewFromFloat(1.5)}, + {fixedpoint.NewFromFloat(120.0), fixedpoint.NewFromFloat(2.5)}, + }, + } + + isValid, err := ob.IsValid() + assert.True(t, isValid) + assert.NoError(t, err) + + ob.Bids = nil + isValid, err = ob.IsValid() + assert.False(t, isValid) + assert.EqualError(t, err, "empty bids") + + ob.Bids = PriceVolumeSlice{ + {fixedpoint.NewFromFloat(80000.0), fixedpoint.NewFromFloat(1.5)}, + {fixedpoint.NewFromFloat(120.0), fixedpoint.NewFromFloat(2.5)}, + } + + ob.Asks = nil + isValid, err = ob.IsValid() + assert.False(t, isValid) + assert.EqualError(t, err, "empty asks") + + ob.Asks = PriceVolumeSlice{ + {fixedpoint.NewFromFloat(100.0), fixedpoint.NewFromFloat(1.5)}, + {fixedpoint.NewFromFloat(90.0), fixedpoint.NewFromFloat(2.5)}, + } + isValid, err = ob.IsValid() + assert.False(t, isValid) + assert.EqualError(t, err, "bid price 80000.000000 > ask price 100.000000") +}