Files
gocryptotrader/exchanges/orderbook/orderbook.go
Ryan O'Hara-Reid eb0571cc9b exchange: binance orderbook fix (#599)
* port orderbook binance management from draft singular asset (spot) processing add additional updates to buffer management

* integrate port

* shifted burden of proof to exchange and remove repairing techniques that obfuscate issues and could caause artifacts

* WIP

* Update exchanges, update tests, update configuration so we can default off on buffer util.

* Add buffer enabled switching to all exchanges and some that are missing, default to off.

* lbtc set not aggregate books

* Addr linter issues

* EOD wip

* optimization and bug fix pass

* clean before test and benchmarking

* add testing/benchmarks to sorting/reversing functions, dropped pointer to slice as we aren't changing slice len or cap

* Add tests and removed ptr for main book as we just ammend amount

* addr exchange test issues

* ci issues

* addr glorious issues

* Addr MCB nits, fixed funding rate book for bitfinex and fixed potential panic on nil book return

* addr linter issues

* updated mistakes

* Fix more tests

* revert bypass

* Addr mcb nits

* fix zero price bug caused by exchange. Filted out bid result rather then unsubscribing. Updated orderbook to L2 so there is no aggregation.

* Allow for zero bid and ask books to be loaded and warn if found.

* remove authentication subscription conflicts as they do not have a channel ID return

* WIP - Batching outbound requests for kraken as they do not give you the partial if you subscribe to do many things.

* finalised outbound request for kraken

* filter zero value due to invalid returned data from exchange, add in max subscription amount and increased outbound batch limit

* expand to max allowed book length & fix issue where they were sending a zero length ask side when we sent a depth of zero

* Updated function comments and added in more realistic book sizing for sort cases

* change map ordering

* amalgamate maps in buffer

* Rm ln

* fix kraken linter issues

* add in buffer initialisation

* increase timout by 30seconds

* Coinbene: Add websocket orderbook length check.

* Engine: Improve switch statement for orderbook summary dissplay.

* Binance: Added tests, remove deadlock

* Exchanges: Change orderbook field -> IsFundingRate

* Orderbook Buffer: Added method to orderbookHolder

* Kraken: removed superfluous integer for sleep

* Bitmex: fixed error return

* cmd/gctcli: force 8 decimal place usage for orderbook streaming

* Kraken: Add checksum and fix bug where we were dropping returned data which was causing artifacts

* Kraken: As per orderbook documentation added in maxdepth field to update to filter depth that goes beyond current scope

* Bitfinex: Tracking down bug on margin-funding, added sequence and checksum validation websocket config on connect (WIP)

* Bitfinex: Complete implementation of checksum

* Bitfinex: Fix funding book insertion and checksum - Dropped updates and deleting items not on book are continuously occuring from stream

* Bitfinex: Fix linter issues

* Bitfinex: Fix even more linter issues.

* Bitmex: Populate orderbook base identification fields to be passed back when error occurrs

* OkGroup: Populate orderbook base identification fields to be passed back when error occurrs

* BTSE: Change string check to 'connect success' to capture multiple user successful strings

* Bitfinex: Updated handling of funding tickers

* Bitfinex: Fix undocumented alignment bug for funding rates

* Bitfinex: Updated error return with more information

* Bitfinex: Change REST fetching to Raw book to keep it in line with websocket implementation. Fix woopsy.

* Localbitcoins: Had to impose a rate limiter to stop errors, fixed return for easier error identification.

* Exchanges: Update failing tests

* LocalBitcoins: Addr nit and bumped time by 1 second for fetching books

* Kraken: Dynamically scale precision based on str return for checksum calculations

* Kraken: Add pair and asset type to validateCRC32 error reponse

* BTSE: Filter out zero amount orderbook price levels in websocket return

* Exchanges: Update orderbook functions to return orderbook base to differentiate errors.

* BTSE: Fix spelling

* Bitmex: Fix error return string

* BTSE: Add orderbook filtering function

* Coinbene: Change wording

* BTSE: Add test for filtering

* Binance: Addr nits, added in variables for buffers and worker amounts and fixed error log messages

* GolangCI: Remove excess 0

* Binance: Reduces double ups on asset and pair in errors

* Binance: Fix error checking
2021-01-04 17:19:55 +11:00

316 lines
8.9 KiB
Go

package orderbook
import (
"fmt"
"sort"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/dispatch"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/log"
)
// Get checks and returns the orderbook given an exchange name and currency pair
func Get(exchange string, p currency.Pair, a asset.Item) (*Base, error) {
return service.Retrieve(exchange, p, a)
}
// SubscribeOrderbook subcribes to an orderbook and returns a communication
// channel to stream orderbook data updates
func SubscribeOrderbook(exchange string, p currency.Pair, a asset.Item) (dispatch.Pipe, error) {
exchange = strings.ToLower(exchange)
service.Lock()
defer service.Unlock()
book, ok := service.Books[exchange][a][p.Base.Item][p.Quote.Item]
if !ok {
return dispatch.Pipe{},
fmt.Errorf("orderbook item not found for %s %s %s",
exchange,
p,
a)
}
return service.mux.Subscribe(book.Main)
}
// SubscribeToExchangeOrderbooks subcribes to all orderbooks on an exchange
func SubscribeToExchangeOrderbooks(exchange string) (dispatch.Pipe, error) {
service.Lock()
defer service.Unlock()
id, ok := service.Exchange[strings.ToLower(exchange)]
if !ok {
return dispatch.Pipe{}, fmt.Errorf("%s exchange orderbooks not found",
exchange)
}
return service.mux.Subscribe(id)
}
// Update stores orderbook data
func (s *Service) Update(b *Base) error {
name := strings.ToLower(b.ExchangeName)
s.Lock()
m1, ok := s.Books[name]
if !ok {
m1 = make(map[asset.Item]map[*currency.Item]map[*currency.Item]*Book)
s.Books[name] = m1
}
m2, ok := m1[b.AssetType]
if !ok {
m2 = make(map[*currency.Item]map[*currency.Item]*Book)
m1[b.AssetType] = m2
}
m3, ok := m2[b.Pair.Base.Item]
if !ok {
m3 = make(map[*currency.Item]*Book)
m2[b.Pair.Base.Item] = m3
}
book, ok := m3[b.Pair.Quote.Item]
if !ok {
book = new(Book)
m3[b.Pair.Quote.Item] = book
err := s.SetNewData(b, book, name)
s.Unlock()
return err
}
book.b.Bids = append(b.Bids[:0:0], b.Bids...) // nolint:gocritic // Short hand to not use make and copy
book.b.Asks = append(b.Asks[:0:0], b.Asks...) // nolint:gocritic // Short hand to not use make and copy
book.b.LastUpdated = b.LastUpdated
ids := append(book.Assoc, book.Main)
s.Unlock()
return s.mux.Publish(ids, b)
}
// SetNewData sets new data
func (s *Service) SetNewData(ob *Base, book *Book, exch string) error {
var err error
book.Assoc, err = s.getAssociations(strings.ToLower(exch))
if err != nil {
return err
}
book.Main, err = s.mux.GetID()
if err != nil {
return err
}
// Below instigates orderbook item separation so we can ensure, in the event
// of a simultaneous update via websocket/rest/fix, we don't affect package
// scoped orderbook data which could result in a potential panic
cpy := *ob
cpy.Bids = append(cpy.Bids[:0:0], cpy.Bids...)
cpy.Asks = append(cpy.Asks[:0:0], cpy.Asks...)
book.b = &cpy
return nil
}
// GetAssociations links a singular book with it's dispatch associations
func (s *Service) getAssociations(exch string) ([]uuid.UUID, error) {
var ids []uuid.UUID
exchangeID, ok := s.Exchange[exch]
if !ok {
var err error
exchangeID, err = s.mux.GetID()
if err != nil {
return nil, err
}
s.Exchange[exch] = exchangeID
}
ids = append(ids, exchangeID)
return ids, nil
}
// Retrieve gets orderbook data from the slice
func (s *Service) Retrieve(exchange string, p currency.Pair, a asset.Item) (*Base, error) {
s.Lock()
defer s.Unlock()
m1, ok := s.Books[strings.ToLower(exchange)]
if !ok {
return nil, fmt.Errorf("no orderbooks for %s exchange", exchange)
}
m2, ok := m1[a]
if !ok {
return nil, fmt.Errorf("no orderbooks associated with asset type %s",
a)
}
m3, ok := m2[p.Base.Item]
if !ok {
return nil, fmt.Errorf("no orderbooks associated with base currency %s",
p.Base)
}
book, ok := m3[p.Quote.Item]
if !ok {
return nil, fmt.Errorf("no orderbooks associated with base currency %s",
p.Quote)
}
ob := *book.b
ob.Bids = append(ob.Bids[:0:0], ob.Bids...)
ob.Asks = append(ob.Asks[:0:0], ob.Asks...)
return &ob, nil
}
// TotalBidsAmount returns the total amount of bids and the total orderbook
// bids value
func (b *Base) TotalBidsAmount() (amountCollated, total float64) {
for x := range b.Bids {
amountCollated += b.Bids[x].Amount
total += b.Bids[x].Amount * b.Bids[x].Price
}
return amountCollated, total
}
// TotalAsksAmount returns the total amount of asks and the total orderbook
// asks value
func (b *Base) TotalAsksAmount() (amountCollated, total float64) {
for y := range b.Asks {
amountCollated += b.Asks[y].Amount
total += b.Asks[y].Amount * b.Asks[y].Price
}
return amountCollated, total
}
// Update updates the bids and asks
func (b *Base) Update(bids, asks []Item) {
b.Bids = bids
b.Asks = asks
b.LastUpdated = time.Now()
}
// Verify ensures that the orderbook items are correctly sorted prior to being
// set and will reject any book with incorrect values.
// Bids should always go from a high price to a low price and
// Asks should always go from a low price to a higher price
func (b *Base) Verify() error {
// Checking for both ask and bid lengths being zero has been removed and
// a warning has been put in place some exchanges e.g. LakeBTC return zero
// level books. In the event that there is a massive liquidity change where
// a book dries up, this will still update so we do not traverse potential
// incorrect old data.
if len(b.Asks) == 0 || len(b.Bids) == 0 {
log.Warnf(log.OrderBook,
bookLengthIssue,
b.ExchangeName,
b.Pair,
b.AssetType,
len(b.Bids),
len(b.Asks))
}
for i := range b.Bids {
if b.Bids[i].Price == 0 {
return fmt.Errorf(bidLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errPriceNotSet)
}
if b.Bids[i].Amount <= 0 {
return fmt.Errorf(bidLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errAmountInvalid)
}
if b.IsFundingRate && b.Bids[i].Period == 0 {
return fmt.Errorf(bidLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errPeriodUnset)
}
if i != 0 {
if b.Bids[i].Price > b.Bids[i-1].Price {
return fmt.Errorf(bidLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errOutOfOrder)
}
if !b.NotAggregated && b.Bids[i].Price == b.Bids[i-1].Price {
return fmt.Errorf(bidLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errDuplication)
}
if b.Bids[i].ID != 0 && b.Bids[i].ID == b.Bids[i-1].ID {
return fmt.Errorf(bidLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errIDDuplication)
}
}
}
for i := range b.Asks {
if b.Asks[i].Price == 0 {
return fmt.Errorf(askLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errPriceNotSet)
}
if b.Asks[i].Amount <= 0 {
return fmt.Errorf(askLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errAmountInvalid)
}
if b.IsFundingRate && b.Asks[i].Period == 0 {
return fmt.Errorf(askLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errPeriodUnset)
}
if i != 0 {
if b.Asks[i].Price < b.Asks[i-1].Price {
return fmt.Errorf(askLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errOutOfOrder)
}
if !b.NotAggregated && b.Asks[i].Price == b.Asks[i-1].Price {
return fmt.Errorf(askLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errDuplication)
}
if b.Asks[i].ID != 0 && b.Asks[i].ID == b.Asks[i-1].ID {
return fmt.Errorf(askLoadBookFailure, b.ExchangeName, b.Pair, b.AssetType, errIDDuplication)
}
}
}
return nil
}
// Process processes incoming orderbooks, creating or updating the orderbook
// list
func (b *Base) Process() error {
if b.ExchangeName == "" {
return errExchangeNameUnset
}
if b.Pair.IsEmpty() {
return errPairNotSet
}
if b.AssetType.String() == "" {
return errAssetTypeNotSet
}
if b.LastUpdated.IsZero() {
b.LastUpdated = time.Now()
}
err := b.Verify()
if err != nil {
return err
}
return service.Update(b)
}
// Reverse reverses the order of orderbook items; some bid/asks are
// returned in either ascending or descending order. One bid or ask slice
// depending on whats received can be reversed. This is usually faster than
// using a sort algorithm as the algorithm could be impeded by a worst case time
// complexity when elements are shifted as opposed to just swapping element
// values.
func Reverse(elem []Item) {
eLen := len(elem)
var target int
for i := eLen/2 - 1; i >= 0; i-- {
target = eLen - 1 - i
elem[i], elem[target] = elem[target], elem[i]
}
}
// SortAsks sorts ask items to the correct ascending order if pricing values are
// scattered. If order from exchange is descending consider using the Reverse
// function.
func SortAsks(d []Item) []Item {
sort.Sort(byOBPrice(d))
return d
}
// SortBids sorts bid items to the correct descending order if pricing values
// are scattered. If order from exchange is ascending consider using the Reverse
// function.
func SortBids(d []Item) []Item {
sort.Sort(sort.Reverse(byOBPrice(d)))
return d
}