Engine: Dispatch service (#346)

* Added dispatch service

* Added orderbook streaming capabilities

* Assigned correct orderbook.base exchange name

* Fixed Requested niterinos
Add in cli orderbook QA tool to gctcli
Add exchange orderbook streaming

* Add ticker streaming support through dispatch package

* Added in some more info on error returns for orderbook.go

* fix linter issues

* Fix some issues

* Update

* Fix requested

* move dispatch out of exchanges folder to its own independant folder

* Fix requested

* change orderbook string to tickers

* Limit orderbooks to 50 and made dispatch system more stateless in operation

* lower cases for update/retrieve/sub exchange name

* Adds in asset validation and lower case conversion on cli

* Remove comment

* Moved timer to a higher scope so its not constantly initialised just reset per instance and removed returning unused channel on error

* Rm unused release function in dispatch.go
Reset timer and bleed buffered timer chan if needed in dispatch.go
Added in ticker.Stop() and timer.Stop() functions for worker routine return in dispatch.go
Index aggregated bid and ask functions for orderbook.go
Added in dummy slice for wsorderbook_test.go

* Moved drain to above Reset so potential race would not occur in dispatch.go
Fix various linter issues dispatch.go

* Fix some issues

* change to start/stop service, added in service state change via cli, updated logger

* fix requested

* Add worker amount init spawning

* fix linter issues

* Fix more linter issues

* More fixes

* Fix race issue on releasing pipe channel on a close after shutting down dispatcher system

* Moved all types to dispatch_types.go && remove panic

* Moved types into serperate file && improve test coverage

* RM unnecessary select case for draining channel && fixed error string

* Added orderbook_types file and improved code coverage

* gofmt file

* reinstated select cases on drain because I am silly

* Remove error for drop worker

* Added more test cases

* not checking error issue fix

* remove func causing race in test, this has required protection via an exported function

* set Gemini websocket orderbook exchange name
This commit is contained in:
Ryan O'Hara-Reid
2019-10-03 09:47:37 +10:00
committed by Adrian Gallagher
parent 4a0fcc7f0f
commit db317a2447
42 changed files with 3802 additions and 1019 deletions

View File

@@ -3,191 +3,205 @@ package ticker
import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gofrs/uuid"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/dispatch"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
)
// const values for the ticker package
const (
errExchangeTickerNotFound = "ticker for exchange does not exist"
errPairNotSet = "ticker currency pair not set"
errAssetTypeNotSet = "ticker asset type not set"
errBaseCurrencyNotFound = "ticker base currency not found"
errQuoteCurrencyNotFound = "ticker quote currency not found"
)
// Vars for the ticker package
var (
Tickers []Ticker
m sync.Mutex
)
// Price struct stores the currency pair and pricing information
type Price struct {
Last float64 `json:"Last"`
High float64 `json:"High"`
Low float64 `json:"Low"`
Bid float64 `json:"Bid"`
Ask float64 `json:"Ask"`
Volume float64 `json:"Volume"`
QuoteVolume float64 `json:"QuoteVolume"`
PriceATH float64 `json:"PriceATH"`
Open float64 `json:"Open"`
Close float64 `json:"Close"`
Pair currency.Pair `json:"Pair"`
LastUpdated time.Time
func init() {
service = new(Service)
service.Tickers = make(map[string]map[*currency.Item]map[*currency.Item]map[asset.Item]*Ticker)
service.Exchange = make(map[string]uuid.UUID)
service.mux = dispatch.GetNewMux()
}
// Ticker struct holds the ticker information for a currency pair and type
type Ticker struct {
Price map[string]map[string]map[string]Price
ExchangeName string
}
// SubscribeTicker subcribes to a ticker and returns a communication channel to
// stream new ticker updates
func SubscribeTicker(exchange string, p currency.Pair, a asset.Item) (dispatch.Pipe, error) {
exchange = strings.ToLower(exchange)
service.RLock()
defer service.RUnlock()
// PriceToString returns the string version of a stored price field
func (t *Ticker) PriceToString(p currency.Pair, priceType string, tickerType asset.Item) string {
priceType = strings.ToLower(priceType)
switch priceType {
case "last":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].Last, 'f', -1, 64)
case "high":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].High, 'f', -1, 64)
case "low":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].Low, 'f', -1, 64)
case "bid":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].Bid, 'f', -1, 64)
case "ask":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].Ask, 'f', -1, 64)
case "volume":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].Volume, 'f', -1, 64)
case "ath":
return strconv.FormatFloat(t.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()].PriceATH, 'f', -1, 64)
default:
return ""
tick, ok := service.Tickers[exchange][p.Base.Item][p.Quote.Item][a]
if !ok {
return dispatch.Pipe{}, fmt.Errorf("ticker item not found for %s %s %s",
exchange,
p,
a)
}
return service.mux.Subscribe(tick.Main)
}
// SubscribeToExchangeTickers subcribes to all tickers on an exchange
func SubscribeToExchangeTickers(exchange string) (dispatch.Pipe, error) {
exchange = strings.ToLower(exchange)
service.RLock()
defer service.RUnlock()
id, ok := service.Exchange[exchange]
if !ok {
return dispatch.Pipe{}, fmt.Errorf("%s exchange tickers not found",
exchange)
}
return service.mux.Subscribe(id)
}
// GetTicker checks and returns a requested ticker if it exists
func GetTicker(exchange string, p currency.Pair, tickerType asset.Item) (Price, error) {
ticker, err := GetTickerByExchange(exchange)
if err != nil {
return Price{}, err
exchange = strings.ToLower(exchange)
service.RLock()
defer service.RUnlock()
if service.Tickers[exchange] == nil {
return Price{}, fmt.Errorf("no tickers for %s exchange", exchange)
}
if !BaseCurrencyExists(exchange, p.Base) {
return Price{}, errors.New(errBaseCurrencyNotFound)
if service.Tickers[exchange][p.Base.Item] == nil {
return Price{}, fmt.Errorf("no tickers associated with base currency %s",
p.Base)
}
if !QuoteCurrencyExists(exchange, p) {
return Price{}, errors.New(errQuoteCurrencyNotFound)
if service.Tickers[exchange][p.Base.Item][p.Quote.Item] == nil {
return Price{}, fmt.Errorf("no tickers associated with quote currency %s",
p.Quote)
}
return ticker.Price[p.Base.Upper().String()][p.Quote.Upper().String()][tickerType.String()], nil
}
// GetTickerByExchange returns an exchange Ticker
func GetTickerByExchange(exchange string) (*Ticker, error) {
m.Lock()
defer m.Unlock()
for x := range Tickers {
if Tickers[x].ExchangeName == exchange {
return &Tickers[x], nil
}
if service.Tickers[exchange][p.Base.Item][p.Quote.Item][tickerType] == nil {
return Price{}, fmt.Errorf("no tickers associated with asset type %s",
tickerType)
}
return nil, errors.New(errExchangeTickerNotFound)
}
// BaseCurrencyExists checks to see if the base currency of the ticker map
// exists
func BaseCurrencyExists(exchange string, currency currency.Code) bool {
m.Lock()
defer m.Unlock()
for _, y := range Tickers {
if y.ExchangeName == exchange {
if _, ok := y.Price[currency.Upper().String()]; ok {
return true
}
}
}
return false
}
// QuoteCurrencyExists checks to see if the quote currency of the ticker map
// exists
func QuoteCurrencyExists(exchange string, p currency.Pair) bool {
m.Lock()
defer m.Unlock()
for _, y := range Tickers {
if y.ExchangeName == exchange {
if _, ok := y.Price[p.Base.Upper().String()]; ok {
if _, ok := y.Price[p.Base.Upper().String()][p.Quote.Upper().String()]; ok {
return true
}
}
}
}
return false
}
// CreateNewTicker creates a new Ticker
func CreateNewTicker(exchangeName string, tickerNew *Price, tickerType asset.Item) Ticker {
m.Lock()
defer m.Unlock()
ticker := Ticker{}
ticker.ExchangeName = exchangeName
ticker.Price = make(map[string]map[string]map[string]Price)
a := make(map[string]map[string]Price)
b := make(map[string]Price)
b[tickerType.String()] = *tickerNew
a[tickerNew.Pair.Quote.Upper().String()] = b
ticker.Price[tickerNew.Pair.Base.Upper().String()] = a
Tickers = append(Tickers, ticker)
return ticker
return service.Tickers[exchange][p.Base.Item][p.Quote.Item][tickerType].Price, nil
}
// ProcessTicker processes incoming tickers, creating or updating the Tickers
// list
func ProcessTicker(exchangeName string, tickerNew *Price, assetType asset.Item) error {
if exchangeName == "" {
return fmt.Errorf(errExchangeNameUnset)
}
tickerNew.ExchangeName = strings.ToLower(exchangeName)
if tickerNew.Pair.IsEmpty() {
return fmt.Errorf("%v %v", exchangeName, errPairNotSet)
return fmt.Errorf("%s %s", exchangeName, errPairNotSet)
}
if assetType == "" {
return fmt.Errorf("%v %v %v", exchangeName, tickerNew.Pair.String(), errAssetTypeNotSet)
return fmt.Errorf("%s %s %s", exchangeName,
tickerNew.Pair,
errAssetTypeNotSet)
}
tickerNew.AssetType = assetType
if tickerNew.LastUpdated.IsZero() {
tickerNew.LastUpdated = time.Now()
}
ticker, err := GetTickerByExchange(exchangeName)
return service.Update(tickerNew)
}
// Update updates ticker price
func (s *Service) Update(p *Price) error {
var ids []uuid.UUID
s.Lock()
switch {
case s.Tickers[p.ExchangeName] == nil:
s.Tickers[p.ExchangeName] = make(map[*currency.Item]map[*currency.Item]map[asset.Item]*Ticker)
s.Tickers[p.ExchangeName][p.Pair.Base.Item] = make(map[*currency.Item]map[asset.Item]*Ticker)
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item] = make(map[asset.Item]*Ticker)
err := s.SetItemID(p)
if err != nil {
s.Unlock()
return err
}
case s.Tickers[p.ExchangeName][p.Pair.Base.Item] == nil:
s.Tickers[p.ExchangeName][p.Pair.Base.Item] = make(map[*currency.Item]map[asset.Item]*Ticker)
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item] = make(map[asset.Item]*Ticker)
err := s.SetItemID(p)
if err != nil {
s.Unlock()
return err
}
case s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item] == nil:
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item] = make(map[asset.Item]*Ticker)
err := s.SetItemID(p)
if err != nil {
s.Unlock()
return err
}
case s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType] == nil:
err := s.SetItemID(p)
if err != nil {
s.Unlock()
return err
}
default:
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Last = p.Last
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].High = p.High
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Low = p.Low
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Bid = p.Bid
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Ask = p.Ask
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Volume = p.Volume
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].QuoteVolume = p.QuoteVolume
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].PriceATH = p.PriceATH
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Open = p.Open
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Close = p.Close
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].LastUpdated = p.LastUpdated
ids = s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Assoc
ids = append(ids, s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType].Main)
}
s.Unlock()
return s.mux.Publish(ids, p)
}
// SetItemID retrieves and sets dispatch mux publish IDs
func (s *Service) SetItemID(p *Price) error {
if p == nil {
return errors.New(errTickerPriceIsNil)
}
ids, err := s.GetAssociations(p)
if err != nil {
CreateNewTicker(exchangeName, tickerNew, assetType)
return nil
return err
}
singleID, err := s.mux.GetID()
if err != nil {
return err
}
if BaseCurrencyExists(exchangeName, tickerNew.Pair.Base) {
m.Lock()
a := make(map[string]Price)
a[assetType.String()] = *tickerNew
ticker.Price[tickerNew.Pair.Base.Upper().String()][tickerNew.Pair.Quote.Upper().String()] = a
m.Unlock()
return nil
}
m.Lock()
a := make(map[string]map[string]Price)
b := make(map[string]Price)
b[assetType.String()] = *tickerNew
a[tickerNew.Pair.Quote.Upper().String()] = b
ticker.Price[tickerNew.Pair.Base.Upper().String()] = a
m.Unlock()
s.Tickers[p.ExchangeName][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType] = &Ticker{Price: *p,
Main: singleID,
Assoc: ids}
return nil
}
// GetAssociations links a singular book with it's dispatch associations
func (s *Service) GetAssociations(p *Price) ([]uuid.UUID, error) {
if p == nil || *p == (Price{}) {
return nil, errors.New(errTickerPriceIsNil)
}
var ids []uuid.UUID
exchangeID, ok := s.Exchange[p.ExchangeName]
if !ok {
var err error
exchangeID, err = s.mux.GetID()
if err != nil {
return nil, err
}
s.Exchange[p.ExchangeName] = exchangeID
}
ids = append(ids, exchangeID)
return ids, nil
}

View File

@@ -1,55 +1,94 @@
package ticker
import (
"log"
"math/rand"
"reflect"
"os"
"strconv"
"sync"
"testing"
"time"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/dispatch"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
)
func TestPriceToString(t *testing.T) {
newPair := currency.NewPairFromStrings("BTC", "USD")
priceStruct := Price{
Pair: newPair,
Last: 1200,
High: 1298,
Low: 1148,
Bid: 1195,
Ask: 1220,
Volume: 5,
PriceATH: 1337,
func TestMain(m *testing.M) {
err := dispatch.Start(1)
if err != nil {
log.Fatal(err)
}
newTicker := CreateNewTicker("ANX", &priceStruct, asset.Spot)
cpyMux = service.mux
if newTicker.PriceToString(newPair, "last", asset.Spot) != "1200" {
t.Error("Test Failed - ticker PriceToString last value is incorrect")
os.Exit(m.Run())
}
var cpyMux *dispatch.Mux
func TestSubscribeTicker(t *testing.T) {
_, err := SubscribeTicker("", currency.Pair{}, asset.Item(""))
if err == nil {
t.Error("error cannot be nil")
}
if newTicker.PriceToString(newPair, "high", asset.Spot) != "1298" {
t.Error("Test Failed - ticker PriceToString high value is incorrect")
p := currency.NewPair(currency.BTC, currency.USD)
// force error
service.mux = nil
err = ProcessTicker("subscribetest", &Price{Pair: p}, asset.Spot)
if err == nil {
t.Error("error cannot be nil")
}
if newTicker.PriceToString(newPair, "low", asset.Spot) != "1148" {
t.Error("Test Failed - ticker PriceToString low value is incorrect")
sillyP := p
sillyP.Base = currency.GALA_NEO
err = ProcessTicker("subscribetest", &Price{Pair: sillyP}, asset.Spot)
if err == nil {
t.Error("error cannot be nil")
}
if newTicker.PriceToString(newPair, "bid", asset.Spot) != "1195" {
t.Error("Test Failed - ticker PriceToString bid value is incorrect")
sillyP.Quote = currency.AAA
err = ProcessTicker("subscribetest", &Price{Pair: sillyP}, asset.Spot)
if err == nil {
t.Error("error cannot be nil")
}
if newTicker.PriceToString(newPair, "ask", asset.Spot) != "1220" {
t.Error("Test Failed - ticker PriceToString ask value is incorrect")
err = ProcessTicker("subscribetest", &Price{Pair: sillyP}, "silly")
if err == nil {
t.Error("error cannot be nil")
}
if newTicker.PriceToString(newPair, "volume", asset.Spot) != "5" {
t.Error("Test Failed - ticker PriceToString volume value is incorrect")
// reinstate mux
service.mux = cpyMux
err = ProcessTicker("subscribetest", &Price{Pair: p}, asset.Spot)
if err != nil {
t.Error("error cannot be nil")
}
if newTicker.PriceToString(newPair, "ath", asset.Spot) != "1337" {
t.Error("Test Failed - ticker PriceToString ath value is incorrect")
_, err = SubscribeTicker("subscribetest", p, asset.Spot)
if err != nil {
t.Error("cannot subscribe to ticker", err)
}
if newTicker.PriceToString(newPair, "obtuse", asset.Spot) != "" {
t.Error("Test Failed - ticker PriceToString obtuse value is incorrect")
}
func TestSubscribeToExchangeTickers(t *testing.T) {
_, err := SubscribeToExchangeTickers("")
if err == nil {
t.Error("error cannot be nil")
}
p := currency.NewPair(currency.BTC, currency.USD)
err = ProcessTicker("subscribeExchangeTest", &Price{Pair: p}, asset.Spot)
if err != nil {
t.Error(err)
}
_, err = SubscribeToExchangeTickers("subscribeExchangeTest")
if err != nil {
t.Error("error cannot be nil", err)
}
}
@@ -111,142 +150,25 @@ func TestGetTicker(t *testing.T) {
if tickerPrice.PriceATH != 9001 {
t.Error("Test Failed - ticker tickerPrice.PriceATH value is incorrect")
}
}
func TestGetTickerByExchange(t *testing.T) {
newPair := currency.NewPairFromStrings("BTC", "USD")
priceStruct := Price{
Pair: newPair,
Last: 1200,
High: 1298,
Low: 1148,
Bid: 1195,
Ask: 1220,
Volume: 5,
PriceATH: 1337,
_, err = GetTicker("bitfinex", newPair, "meowCats")
if err == nil {
t.Error("Test Failed - Ticker GetTicker error cannot be nil")
}
anxTicker := CreateNewTicker("ANX", &priceStruct, asset.Spot)
Tickers = append(Tickers, anxTicker)
tickerPtr, err := GetTickerByExchange("ANX")
err = ProcessTicker("bitfinex", &priceStruct, "meowCats")
if err != nil {
t.Errorf("Test Failed - GetTickerByExchange init error: %s", err)
}
if tickerPtr.ExchangeName != "ANX" {
t.Error("Test Failed - GetTickerByExchange ExchangeName value is incorrect")
}
}
func TestBaseCurrencyExists(t *testing.T) {
newPair := currency.NewPairFromStrings("BTC", "USD")
priceStruct := Price{
Pair: newPair,
Last: 1200,
High: 1298,
Low: 1148,
Bid: 1195,
Ask: 1220,
Volume: 5,
PriceATH: 1337,
t.Fatal("Test failed. ProcessTicker error", err)
}
alphaTicker := CreateNewTicker("alphapoint", &priceStruct, asset.Spot)
Tickers = append(Tickers, alphaTicker)
if !BaseCurrencyExists("alphapoint", currency.BTC) {
t.Error("Test Failed - BaseCurrencyExists1 value return is incorrect")
}
if BaseCurrencyExists("alphapoint", currency.NewCode("CATS")) {
t.Error("Test Failed - BaseCurrencyExists2 value return is incorrect")
}
}
func TestQuoteCurrencyExists(t *testing.T) {
t.Parallel()
newPair := currency.NewPairFromStrings("BTC", "USD")
priceStruct := Price{
Pair: newPair,
Last: 1200,
High: 1298,
Low: 1148,
Bid: 1195,
Ask: 1220,
Volume: 5,
PriceATH: 1337,
}
bitstampTicker := CreateNewTicker("bitstamp", &priceStruct, asset.Spot)
Tickers = append(Tickers, bitstampTicker)
if !QuoteCurrencyExists("bitstamp", newPair) {
t.Error("Test Failed - QuoteCurrencyExists1 value return is incorrect")
}
newPair.Quote = currency.NewCode("DOGS")
if QuoteCurrencyExists("bitstamp", newPair) {
t.Error("Test Failed - QuoteCurrencyExists2 value return is incorrect")
}
}
func TestCreateNewTicker(t *testing.T) {
const float64Type = "float64"
newPair := currency.NewPairFromStrings("BTC", "USD")
priceStruct := Price{
Pair: newPair,
Last: 1200,
High: 1298,
Low: 1148,
Bid: 1195,
Ask: 1220,
Volume: 5,
PriceATH: 1337,
}
newTicker := CreateNewTicker("ANX", &priceStruct, asset.Spot)
if reflect.ValueOf(newTicker).NumField() != 2 {
t.Error("Test Failed - ticker CreateNewTicker struct change/or updated")
}
if reflect.TypeOf(newTicker.ExchangeName).String() != "string" {
t.Error("Test Failed - ticker CreateNewTicker.ExchangeName value is not a string")
}
if newTicker.ExchangeName != "ANX" {
t.Error("Test Failed - ticker CreateNewTicker.ExchangeName value is not ANX")
}
if !newTicker.Price[currency.BTC.Upper().String()][currency.USD.Upper().String()][asset.Spot.String()].Pair.Equal(newPair) {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Pair.Pair().String() value is not expected 'BTCUSD'")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].Ask).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Ask value is not a float64")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].Bid).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Bid value is not a float64")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].Pair).String() != "currency.Pair" {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].CurrencyPair value is not a currency.Pair")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].High).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].High value is not a float64")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].Last).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Last value is not a float64")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].Low).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Low value is not a float64")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].PriceATH).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].PriceATH value is not a float64")
}
if reflect.TypeOf(newTicker.Price["BTC"]["USD"][asset.Spot.String()].Volume).String() != float64Type {
t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Volume value is not a float64")
// process update again
err = ProcessTicker("bitfinex", &priceStruct, "meowCats")
if err != nil {
t.Fatal("Test failed. ProcessTicker error", err)
}
}
func TestProcessTicker(t *testing.T) { // non-appending function to tickers
Tickers = []Ticker{}
exchName := "bitstamp"
newPair := currency.NewPairFromStrings("BTC", "USD")
priceStruct := Price{
@@ -259,8 +181,13 @@ func TestProcessTicker(t *testing.T) { // non-appending function to tickers
PriceATH: 1337,
}
err := ProcessTicker("", &priceStruct, asset.Spot)
if err == nil {
t.Fatal("empty exchange should throw an err")
}
// test for empty pair
err := ProcessTicker(exchName, &priceStruct, asset.Spot)
err = ProcessTicker(exchName, &priceStruct, asset.Spot)
if err == nil {
t.Fatal("empty pair should throw an err")
}
@@ -389,5 +316,44 @@ func TestProcessTicker(t *testing.T) { // non-appending function to tickers
}
}
wg.Wait()
}
func TestSetItemID(t *testing.T) {
err := service.SetItemID(nil)
if err == nil {
t.Error("error cannot be nil")
}
err = service.SetItemID(&Price{})
if err == nil {
t.Error("error cannot be nil")
}
p := currency.NewPair(currency.CYC, currency.CYG)
service.mux = nil
err = service.SetItemID(&Price{Pair: p, ExchangeName: "SetItemID"})
if err == nil {
t.Error("error cannot be nil")
}
service.mux = cpyMux
}
func TestGetAssociation(t *testing.T) {
_, err := service.GetAssociations(nil)
if err == nil {
t.Error("error cannot be nil ")
}
p := currency.NewPair(currency.CYC, currency.CYG)
service.mux = nil
_, err = service.GetAssociations(&Price{Pair: p, ExchangeName: "GetAssociation"})
if err == nil {
t.Error("error cannot be nil ")
}
service.mux = cpyMux
}

View File

@@ -0,0 +1,57 @@
package ticker
import (
"sync"
"time"
"github.com/gofrs/uuid"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/dispatch"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
)
// const values for the ticker package
const (
errExchangeNameUnset = "ticker exchange name not set"
errPairNotSet = "ticker currency pair not set"
errAssetTypeNotSet = "ticker asset type not set"
errTickerPriceIsNil = "ticker price is nil"
)
// Vars for the ticker package
var (
service *Service
)
// Service holds ticker information for each individual exchange
type Service struct {
Tickers map[string]map[*currency.Item]map[*currency.Item]map[asset.Item]*Ticker
Exchange map[string]uuid.UUID
mux *dispatch.Mux
sync.RWMutex
}
// Price struct stores the currency pair and pricing information
type Price struct {
Last float64 `json:"Last"`
High float64 `json:"High"`
Low float64 `json:"Low"`
Bid float64 `json:"Bid"`
Ask float64 `json:"Ask"`
Volume float64 `json:"Volume"`
QuoteVolume float64 `json:"QuoteVolume"`
PriceATH float64 `json:"PriceATH"`
Open float64 `json:"Open"`
Close float64 `json:"Close"`
Pair currency.Pair `json:"Pair"`
ExchangeName string `json:"exchangeName"`
AssetType asset.Item `json:"assetType"`
LastUpdated time.Time
}
// Ticker struct holds the ticker information for a currency pair and type
type Ticker struct {
Price
Main uuid.UUID
Assoc []uuid.UUID
}