From e7b469638e0e70fd3340758b90c44e17bb0c7578 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 27 Mar 2017 17:50:20 +1100 Subject: [PATCH 01/37] Added test support for bitfinex --- common/common.go | 8 +- exchanges/bitfinex/bitfinex.go | 23 +- exchanges/bitfinex/bitfinex_test.go | 983 ++++++++++++++++++++++++++++ main.go | 1 + 4 files changed, 1009 insertions(+), 6 deletions(-) create mode 100644 exchanges/bitfinex/bitfinex_test.go diff --git a/common/common.go b/common/common.go index f464a151..94c2f6ce 100644 --- a/common/common.go +++ b/common/common.go @@ -1,6 +1,7 @@ package common import ( + //"bytes" "crypto/hmac" "crypto/md5" "crypto/sha1" @@ -122,6 +123,11 @@ func StringContains(input, substring string) bool { return strings.Contains(input, substring) } +func DataContains(haystack []string, needle string) bool { + data := strings.Join(haystack, ",") + return strings.Contains(data, needle) +} + func JoinStrings(input []string, seperator string) string { return strings.Join(input, seperator) } @@ -253,8 +259,8 @@ func SendHTTPGetRequest(url string, jsonDecode bool, result interface{}) (err er if jsonDecode { err := JSONDecode(contents, &result) - if err != nil { + log.Println(string(contents[:])) return err } } else { diff --git a/exchanges/bitfinex/bitfinex.go b/exchanges/bitfinex/bitfinex.go index 05fb39c8..1f770082 100644 --- a/exchanges/bitfinex/bitfinex.go +++ b/exchanges/bitfinex/bitfinex.go @@ -95,8 +95,8 @@ func (b *Bitfinex) GetTicker(symbol string, values url.Values) (BitfinexTicker, return response, nil } -func (b *Bitfinex) GetStats(symbol string) (BitfinexStats, error) { - response := BitfinexStats{} +func (b *Bitfinex) GetStats(symbol string) ([]BitfinexStats, error) { + response := []BitfinexStats{} err := common.SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_STATS+symbol, true, &response) if err != nil { return response, err @@ -105,6 +105,9 @@ func (b *Bitfinex) GetStats(symbol string) (BitfinexStats, error) { } func (b *Bitfinex) GetLendbook(symbol string, values url.Values) (BitfinexLendbook, error) { + if len(symbol) == 6 { + symbol = symbol[:3] + } path := common.EncodeURLValues(BITFINEX_API_URL+BITFINEX_LENDBOOK+symbol, values) response := BitfinexLendbook{} err := common.SendHTTPGetRequest(path, true, &response) @@ -167,7 +170,7 @@ func (b *Bitfinex) GetAccountInfo() ([]BitfinexAccountInfo, error) { err := b.SendAuthenticatedHTTPRequest("POST", BITFINEX_ACCOUNT_INFO, nil, &response) if err != nil { - log.Println(err) + return response, err } return response, nil } @@ -534,7 +537,6 @@ func (b *Bitfinex) CloseMarginFunding(SwapID int64) (BitfinexOffer, error) { func (b *Bitfinex) GetAccountBalance() ([]BitfinexBalance, error) { response := []BitfinexBalance{} err := b.SendAuthenticatedHTTPRequest("POST", BITFINEX_BALANCES, nil, &response) - if err != nil { return nil, err } @@ -587,6 +589,10 @@ func (b *Bitfinex) Withdrawal(withdrawType, wallet, address string, amount float } func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[string]interface{}, result interface{}) (err error) { + if len(b.APIKey) == 0 { + return errors.New("SendAuthenticatedHTTPRequest: Invalid API key") + } + request := make(map[string]interface{}) request["request"] = fmt.Sprintf("/v%s/%s", BITFINEX_API_VERSION, path) request["nonce"] = strconv.FormatInt(time.Now().UnixNano(), 10) @@ -615,6 +621,13 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ headers["X-BFX-SIGNATURE"] = common.HexEncodeToString(hmac) resp, err := common.SendHTTPRequest(method, BITFINEX_API_URL+path, headers, strings.NewReader("")) + if err != nil { + return err + } + + if strings.Contains(resp, "message") { + return errors.New("SendAuthenticatedHTTPRequest: " + resp[11:]) + } if b.Verbose { log.Printf("Recieved raw: \n%s\n", resp) @@ -623,7 +636,7 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ err = common.JSONDecode([]byte(resp), &result) if err != nil { - return errors.New("Unable to JSON Unmarshal response.") + return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON Unmarshal response.") } return nil diff --git a/exchanges/bitfinex/bitfinex_test.go b/exchanges/bitfinex/bitfinex_test.go new file mode 100644 index 00000000..d4f0bf12 --- /dev/null +++ b/exchanges/bitfinex/bitfinex_test.go @@ -0,0 +1,983 @@ +package bitfinex + +import ( + "log" + "net/url" + "reflect" + "strconv" + "testing" +) + +var ACCOUNT_LIVE_TEST bool = true + +//Live Testing -- TestBitfinexGetTicker() +func TestBitfinexGetTicker(t *testing.T) { + t.Parallel() + bitfinex := Bitfinex{} + + response, err := bitfinex.GetTicker("BTCUSD", url.Values{}) + if err != nil { + t.Error("BitfinexGetTicker init error: ", err) + } + if reflect.ValueOf(response).NumField() != 8 { + t.Error("BitfinexGetTicker struct change/or updated") + } + if reflect.TypeOf(response.Timestamp).String() != "string" { + t.Error("Bitfinex ticker.Timestamp value is not a string variable") + } + if reflect.TypeOf(response.Ask).String() != "float64" { + t.Error("Bitfinex ticker.Ask value is not a float64 variable") + } + if reflect.TypeOf(response.Bid).String() != "float64" { + t.Error("Bitfinex ticker.Bid value is not a float64 variable") + } + if reflect.TypeOf(response.High).String() != "float64" { + t.Error("Bitfinex ticker.High value is not a float64 variable") + } + if reflect.TypeOf(response.Last).String() != "float64" { + t.Error("Bitfinex ticker.Last value is not a float64 variable") + } + if reflect.TypeOf(response.Low).String() != "float64" { + t.Error("Bitfinex ticker.Low value is not a float64 variable") + } + if reflect.TypeOf(response.Mid).String() != "float64" { + t.Error("Bitfinex ticker.Mid value is not a float64 variable") + } + if reflect.TypeOf(response.Volume).String() != "float64" { + t.Error("Bitfinex ticker.Volume value is not a float64 variable") + } + + responseTimestamp, err := strconv.ParseFloat(response.Timestamp, 64) + if err != nil { + t.Error("ticker.Timestamp value cannot be converted to a float64") + } + if responseTimestamp <= 0 { + t.Error("ticker.Timestamp value is negative or 0") + } + if response.Ask < 0 { + t.Error("ticker.Ask value is negative") + } + if response.Bid < 0 { + t.Error("ticker.Bid value is negative") + } + if response.High < 0 { + t.Error("ticker.High value is negative") + } + if response.Last < 0 { + t.Error("ticker.Last value is negative") + } + if response.Low < 0 { + t.Error("ticker.Low value is negative") + } + if response.Mid < 0 { + t.Error("ticker.Mid value is negative") + } + if response.Volume < 0 { + t.Error("ticker.ask value is negative") + } +} + +//Live Testing -- TestBitfinexGetStats() +func TestBitfinexGetStats(t *testing.T) { + t.Parallel() + BitfinexGetStatsTest := Bitfinex{} + + response, err := BitfinexGetStatsTest.GetStats("BTCUSD") + if err != nil { + t.Error("BitfinexGetStatsTest init error: ", err) + } + if reflect.ValueOf(response[0]).NumField() != 2 { + t.Error("BitfinexGetTicker []struct change/or updated") + } + if reflect.TypeOf(response[0].Period).String() != "int64" { + t.Error("Bitfinex Getstats.Period is not an int64") + } + if reflect.TypeOf(response[0].Volume).String() != "float64" { + t.Error("Bitfiniex Getstats.Volume is not a float64") + } + + for _, explicitResponse := range response { + if explicitResponse.Period <= 0 { + t.Error("response.Period value is negative or zero") + } + if explicitResponse.Volume < 0 { + t.Error("response.Volume value is negative") + } + } +} + +//Live Testing -- TestBitfinexGetLendbook() +func TestBitfinexGetLendbook(t *testing.T) { + t.Parallel() + BitfinexGetLendbook := Bitfinex{} + + response, err := BitfinexGetLendbook.GetLendbook("BTCUSD", url.Values{}) + if err != nil { + t.Error("BitfinexGetLendbook init error: ", err) + } + if reflect.ValueOf(response).NumField() != 2 { + t.Error("BitfinexGetLendbook struct change/or updated") + } + if reflect.ValueOf(response.Asks[0]).NumField() != 5 { + t.Error("BitfinexGetLendbook GetLendbook.Asks []struct change/or updated") + } + if reflect.TypeOf(response.Asks[0].Amount).String() != "float64" { + t.Error("Bitfinex GetLendbook.Asks.Amount is not a float64") + } + if reflect.TypeOf(response.Asks[0].FlashReturnRate).String() != "string" { + t.Error("Bitfinex GetLendbook.Asks.FlashReturnRate is not a string") + } + if reflect.TypeOf(response.Asks[0].Period).String() != "int" { + t.Error("Bitfinex GetLendbook.Asks.Period is not an int") + } + if reflect.TypeOf(response.Asks[0].Rate).String() != "float64" { + t.Error("Bitfinex GetLendbook.Asks.Rate is not a float64") + } + if reflect.ValueOf(response.Bids[0]).NumField() != 5 { + t.Error("BitfinexGetLendbook GetLendbook.Bids []struct change/or updated") + } + if reflect.TypeOf(response.Bids[0].Amount).String() != "float64" { + t.Error("Bitfinex GetLendbook.Bids.Amount is not a float64") + } + if reflect.TypeOf(response.Bids[0].FlashReturnRate).String() != "string" { + t.Error("Bitfinex GetLendbook.Bids.FlashReturnRate is not a string") + } + if reflect.TypeOf(response.Bids[0].Period).String() != "int" { + t.Error("Bitfinex GetLendbook.Bids.Period is not an int") + } + if reflect.TypeOf(response.Bids[0].Rate).String() != "float64" { + t.Error("Bitfinex GetLendbook.Bids.Rate is not a float64") + } + + for _, asks := range response.Asks { + responseTimestamp, err := strconv.ParseFloat(asks.Timestamp, 64) + if err != nil { + t.Error("Could not convert Bitfinex GetLendbook.Asks.Timestamp into float64") + } + if asks.Amount <= 0 { + t.Error("Bitfinex GetLendbook.Asks.Amount is negative or 0") + } + if asks.FlashReturnRate != "No" && asks.FlashReturnRate != "Yes" { + t.Error("Bitfinex GetLendbook.Bids.FlashReturnRate incorrect string") + } + if asks.Period <= 0 { + t.Error("Bitfinex GetLendbook.Asks.Period is negative or 0") + } + if asks.Rate <= 0 { + t.Error("Bitfinex GetLendbook.Asks.Rate is negative or 0") + } + if responseTimestamp <= 0 { + t.Error("Bitfinex GetLendbook.Asks.Timestamp is negative or 0") + } + } + + for _, bids := range response.Bids { + responseTimetamp, err := strconv.ParseFloat(bids.Timestamp, 64) + if err != nil { + t.Error("Could not convert Bitfinex GetLendbook.Bids.Timestamp into float64") + } + if bids.Amount <= 0 { + t.Error("Bitfinex GetLendbook.Bids.Amount is negative or 0") + } + if bids.FlashReturnRate == "no" || bids.FlashReturnRate == "yes" { + t.Error("Bitfinex GetLendbook.Bids.FlashReturnRate incorrect string") + } + if bids.Period <= 0 { + t.Error("Bitfinex GetLendbook.Bids.Period is negative or 0") + } + if bids.Rate <= 0 { + t.Error("Bitfinex GetLendbook.Bids.Rate is negative or 0") + } + if responseTimetamp <= 0 { + t.Error("Bitfinex GetLendbook.Bids.Timestamp is negative or 0") + } + } +} + +//Live Testing -- TestBitfinexGetOrderbook() +func TestBitfinexGetOrderbook(t *testing.T) { + t.Parallel() + BitfinexGetOrderbook := Bitfinex{} + + orderBook, err := BitfinexGetOrderbook.GetOrderbook("BTCUSD", url.Values{}) + if err != nil { + t.Error("BitfinexGetOrderbook init error: ", err) + } + if reflect.ValueOf(orderBook).NumField() != 2 { + t.Error("BitfinexGetOrderbook struct change/or updated") + } + if reflect.ValueOf(orderBook.Asks[0]).NumField() != 3 { + t.Error("BitfinexGetOrderbook []struct change/or updated") + } + if reflect.ValueOf(orderBook.Bids[0]).NumField() != 3 { + t.Error("BitfinexGetOrderbook []struct change/or updated") + } + if reflect.TypeOf(orderBook.Asks[0].Amount).String() != "string" { + t.Error("Bitfinex GetOrderbook.Bids.Amount is not a string") + } + if reflect.TypeOf(orderBook.Asks[0].Price).String() != "string" { + t.Error("Bitfinex GetOrderbook.Bids.Amount is not a string") + } + if reflect.TypeOf(orderBook.Asks[0].Timestamp).String() != "string" { + t.Error("Bitfinex GetOrderbook.Bids.Amount is not a string") + } + if reflect.TypeOf(orderBook.Bids[0].Amount).String() != "string" { + t.Error("Bitfinex GetOrderbook.Bids.Amount is not a string") + } + if reflect.TypeOf(orderBook.Bids[0].Price).String() != "string" { + t.Error("Bitfinex GetOrderbook.Bids.Amount is not a string") + } + if reflect.TypeOf(orderBook.Bids[0].Timestamp).String() != "string" { + t.Error("Bitfinex GetOrderbook.Bids.Amount is not a string") + } + + for _, asks := range orderBook.Asks { + amount, err := strconv.ParseFloat(asks.Amount, 64) + if err != nil { + t.Error("Cannot convert Bitfinex Orderbook.Asks.Amount into a float64") + } + if amount < 0 { + t.Error("Bitfinex Orderbook.Asks.Amount is negative") + } + price, err2 := strconv.ParseFloat(asks.Price, 64) + if err2 != nil { + t.Error("Cannot convert Bitfinex Orderbook.Asks.Price into a float64") + } + if price < 0 { + t.Error("Bitfinex Orderbook.Asks.Price is negative") + } + timestamp, err3 := strconv.ParseFloat(asks.Timestamp, 64) + if err3 != nil { + t.Error("Cannot convert Bitfinex Orderbook.Asks.timestamp into a float64") + } + if timestamp <= 0 { + t.Error("Bitfinex Orderbook.Asks.Amount is negative or 0") + } + } + + for _, bids := range orderBook.Bids { + amount, err := strconv.ParseFloat(bids.Amount, 64) + if err != nil { + t.Error("Cannot convert Bitfinex Orderbook.bids.Amount into a float64") + } + if amount < 0 { + t.Error("Bitfinex Orderbook.bids.Amount is negative") + } + price, err2 := strconv.ParseFloat(bids.Price, 64) + if err2 != nil { + t.Error("Cannot convert Bitfinex Orderbook.bids.Price into a float64") + } + if price < 0 { + t.Error("Bitfinex Orderbook.bids.Price is negative") + } + timestamp, err3 := strconv.ParseFloat(bids.Timestamp, 64) + if err3 != nil { + t.Error("Cannot convert Bitfinex Orderbook.bids.timestamp into a float64") + } + if timestamp <= 0 { + t.Error("Bitfinex Orderbook.bids.Amount is negative or 0") + } + } +} + +//Live Testing -- TestBitfinexGetTrades() +func TestBitfinexGetTrades(t *testing.T) { + t.Parallel() + BitfinexGetTrades := Bitfinex{} + + trades, err := BitfinexGetTrades.GetTrades("BTCUSD", url.Values{}) + if err != nil { + t.Error("BitfinexGetTrades init error: ", err) + } + if reflect.ValueOf(trades[0]).NumField() != 6 { + t.Error("BitfinexGetTrades struct change/or updated") + } + if reflect.TypeOf(trades[0].Amount).String() != "string" { + t.Error("Bitfinex GetGetTrades.Amount is not a string") + } + if reflect.TypeOf(trades[0].Exchange).String() != "string" { + t.Error("Bitfinex GetGetTrades.Exchange is not a string") + } + if reflect.TypeOf(trades[0].Price).String() != "string" { + t.Error("Bitfinex GetGetTrades.Price is not a string") + } + if reflect.TypeOf(trades[0].Tid).String() != "int64" { + t.Error("Bitfinex GetGetTrades.Tid is not a int64") + } + if reflect.TypeOf(trades[0].Timestamp).String() != "int64" { + t.Error("Bitfinex GetGetTrades.Timestamp is not a int64") + } + if reflect.TypeOf(trades[0].Type).String() != "string" { + t.Error("Bitfinex GetGetTrades.Type is not a string") + } + + for _, explicitTrades := range trades { + amount, err := strconv.ParseFloat(explicitTrades.Amount, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetTrades.Amount into a float64") + } + if amount <= 0 { + t.Error("Bitfinex GetTrades.Amount is negative or 0") + } + if explicitTrades.Exchange != "bitfinex" { + t.Error("Bitfinex GetTrades.Exchange incorrect name") + } + price, err2 := strconv.ParseFloat(explicitTrades.Price, 64) + if err2 != nil { + t.Error("Cannot convert Bitfinex GetTrades.Price into a float64") + } + if price <= 0 { + t.Error("Bitfinex GetTrades.Price is negative or 0") + } + if explicitTrades.Tid <= 0 { + t.Error("Bitfinex GetTrades.Tid is negative or 0") + } + if explicitTrades.Timestamp <= 0 { + t.Error("Bitfinex GetTrades.Timestamp is negative or 0") + } + if explicitTrades.Type != "buy" && explicitTrades.Type != "sell" { + t.Error("Bitfinex GetTrades.Type is wrong") + } + } +} + +//Live Testing -- TestBitfinexGetLends() +func TestBitfinexGetLends(t *testing.T) { + t.Parallel() + BitfinexGetLends := Bitfinex{} + + lends, err := BitfinexGetLends.GetLends("BTC", url.Values{}) + if err != nil { + t.Error("BitfinexGetLends init error: ", err) + } + if reflect.ValueOf(lends[0]).NumField() != 4 { + t.Error("BitfinexGetLends struct change/or updated") + } + if reflect.TypeOf(lends[0].AmountLent).String() != "float64" { + t.Error("Bitfinex GetGetLends.AmountLent is not a float64") + } + if reflect.TypeOf(lends[0].AmountUsed).String() != "float64" { + t.Error("Bitfinex GetGetLends.AmountUsed is not a float64") + } + if reflect.TypeOf(lends[0].Rate).String() != "float64" { + t.Error("Bitfinex GetGetLends.Rate is not a float64") + } + if reflect.TypeOf(lends[0].Timestamp).String() != "int64" { + t.Error("Bitfinex GetGetLends.Timestamp is not a int64") + } + + for _, explicitLends := range lends { + if explicitLends.AmountLent <= 0 { + t.Error("Bitfinex GetLends.AmountLent is negative or 0") + } + if explicitLends.AmountUsed <= 0 { + t.Error("Bitfinex GetLends.AmountUsed is negative or 0") + } + if explicitLends.Rate <= 0 { + t.Error("Bitfinex GetLends.Rate is negative or 0") + } + if explicitLends.Timestamp <= 0 { + t.Error("Bitfinex GetLends.Timestamp is negative or 0") + } + } +} + +//Live Testing -- TestBitfinexGetSymbols() +func TestBitfinexGetSymbols(t *testing.T) { + t.Parallel() + BitfinexGetSymbols := Bitfinex{} + + symbols, err := BitfinexGetSymbols.GetSymbols() + if err != nil { + t.Error("BitfinexGetSymbols init error: ", err) + } + if reflect.TypeOf(symbols[0]).String() != "string" { + t.Error("Bitfinex GetSymbols is not a string") + } + + expectedCurrencies := []string{ + "rrtbtc", + "zecusd", + "zecbtc", + "xmrusd", + "xmrbtc", + "dshusd", + "dshbtc", + "bccbtc", + "bcubtc", + "bccusd", + "bcuusd", + "btcusd", + "ltcusd", + "ltcbtc", + "ethusd", + "ethbtc", + "etcbtc", + "etcusd", + "bfxusd", + "bfxbtc", + "rrtusd", + } + + if len(expectedCurrencies) == len(symbols) { + for _, explicitSymbol := range expectedCurrencies { + for i := 0; i < len(expectedCurrencies); i++ { + if explicitSymbol == symbols[i] { + break + } else if i == (len(expectedCurrencies))-1 { + t.Error("BitfinexGetSymbols currency mismatch with: ", explicitSymbol) + } + } + } + } else if len(expectedCurrencies) > len(symbols) { + t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies > Exchange Currencies") + } else { + t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies < Exchange Currencies") + } +} + +//Live Testing -- TestBitfinexGetSymbolsDetails() +func TestBitfinexGetSymbolsDetails(t *testing.T) { + t.Parallel() + BitfinexGetSymbolsDetails := Bitfinex{} + + symbolDetails, err := BitfinexGetSymbolsDetails.GetSymbolsDetails() + if err != nil { + t.Error("BitfinexGetSymbolsDetails init error: ", err) + } + if reflect.ValueOf(symbolDetails[0]).NumField() != 7 { + t.Error("BitfinexGetSymbolsDetails struct change/or updated") + } + if reflect.TypeOf(symbolDetails[0].Expiration).String() != "string" { + t.Error("Bitfinex GetSymbolsDetails.Expiration is not a string") + } + if reflect.TypeOf(symbolDetails[0].InitialMargin).String() != "float64" { + t.Error("Bitfinex GetSymbolsDetails.InitialMargin is not a float64") + } + if reflect.TypeOf(symbolDetails[0].MaximumOrderSize).String() != "float64" { + t.Error("Bitfinex GetSymbolsDetails.MaximumOrderSize is not a float64") + } + if reflect.TypeOf(symbolDetails[0].MinimumMargin).String() != "float64" { + t.Error("Bitfinex GetSymbolsDetails.MinimumMargin is not a float64") + } + if reflect.TypeOf(symbolDetails[0].MinimumOrderSize).String() != "float64" { + t.Error("Bitfinex GetSymbolsDetails.MinimumOrderSize is not a float64") + } + if reflect.TypeOf(symbolDetails[0].Pair).String() != "string" { + t.Error("Bitfinex GetSymbolsDetails.Pair is not a string") + } + if reflect.TypeOf(symbolDetails[0].PricePrecision).String() != "int" { + t.Error("Bitfinex GetSymbolsDetails.PricePrecision is not a int") + } + + for _, explicitDetails := range symbolDetails { + if explicitDetails.Expiration != "NA" { + expiration, err := strconv.ParseFloat(explicitDetails.Expiration, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetSymbolsDetails.Expiration into a float64") + } + if expiration < 0 { + t.Error("Bitfinex GetSymbolsDetails.Expiration is negative") + } + } + if explicitDetails.InitialMargin <= 0 { + t.Error("Bitfinex GetSymbolsDetails.InitialMargin is negative or 0") + } + if explicitDetails.MaximumOrderSize <= 0 { + t.Error("Bitfinex GetSymbolsDetails.MaximumOrderSize is negative or 0") + } + if explicitDetails.MinimumMargin <= 0 { + t.Error("Bitfinex GetSymbolsDetails.MinimumMargin is negative or 0") + } + if explicitDetails.MinimumOrderSize <= 0 { + t.Error("Bitfinex GetSymbolsDetails.MinimumOrderSize is negative or 0") + } + if len(explicitDetails.Pair) != 6 { + t.Error("Bitfinex GetSymbolsDetails.Pair incorrect length") + } + if explicitDetails.PricePrecision <= 0 { + t.Error("Bitfinex GetSymbolsDetails.PricePrecision is negative or 0") + } + } +} + +//Hybrid Testing -- TestBitfinexGetAccountInfo() +func TestBitfinexGetAccountInfo(t *testing.T) { + t.Parallel() + + expectedCryptoCurrencies := []string{ + "BTC", + "LTC", + "ETH", + "ETC", + "ZEC", + "XMR", + "DSH", + } + + if ACCOUNT_LIVE_TEST { //Live Test + BitfinexGetAccountInfo := Bitfinex{} + accountInfoLive, err := BitfinexGetAccountInfo.GetAccountInfo() + if err != nil { + t.Error("BitfinexGetAccountInfo init error: ", err) + } + if reflect.ValueOf(accountInfoLive[0]).NumField() != 3 { + t.Error("BitfinexGetAccountInfo struct change/or updated") + } + if reflect.TypeOf(accountInfoLive[0].MakerFees).String() != "string" { + t.Error("Bitfinex GetAccountInfo.MakerFees is not a string") + } + if reflect.TypeOf(accountInfoLive[0].TakerFees).String() != "string" { + t.Error("Bitfinex GetAccountInfo.TakerFees is not a string") + } + + if len(expectedCryptoCurrencies) == len(accountInfoLive[0].Fees) { + if !DataContains(expectedCryptoCurrencies, accountInfoLive[0].Fees[0].Pairs) { + t.Error("Bitfinex GetAccountInfo currency mismatch") + } + } else if len(expectedCryptoCurrencies) > len(accountInfoLive[0].Fees) { + t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies > Exchange Currencies") + } else { + t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies < Exchange Currencies") + } + + if len(accountInfoLive[0].Fees) != 7 { + t.Error("Bitfinex GetAccountInfo.Fees incorrect length") + } + + for _, explicitAI := range accountInfoLive { + makerFees, err := strconv.ParseFloat(explicitAI.MakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.MakerFees into float64") + } + if makerFees < 0 { + t.Error("Bitfinex GetAccountInfo.MakerFees is negative") + } + + takerFees, err := strconv.ParseFloat(explicitAI.TakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.TakerFees into float64") + } + if takerFees < 0 { + t.Error("Bitfinex GetAccountInfo.TakerFees is negative") + } + + for _, fees := range explicitAI.Fees { + MakerFees, err := strconv.ParseFloat(fees.MakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.Fees.MakerFees into float64") + } + if MakerFees < 0 { + t.Error("Bitfinex GetAccountInfo.Fees.MakerFees is negative") + } + TakerFees, err := strconv.ParseFloat(fees.TakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.Fees.TakerFees into float64") + } + if TakerFees < 0 { + t.Error("Bitfinex GetAccountInfo.Fees.TakerFees is negative") + } + } + } + + } else { //Non-Live Test + type Fees struct { + Pairs string `json:"pairs"` + MakerFees string `json:"maker_fees"` + TakerFees string `json:"taker_fees"` + } + accountInfoNonLive := [1]BitfinexAccountInfo{} + accountInfoNonLive[0].MakerFees = "0.1" + accountInfoNonLive[0].TakerFees = "0.2" + nonLiveFees := Fees{} + nonLiveFees.MakerFees = "0.1" + nonLiveFees.Pairs = "BTC" + nonLiveFees.TakerFees = "0.2" + accountInfoNonLive[0].Fees = append(accountInfoNonLive[0].Fees, nonLiveFees) + + if reflect.ValueOf(accountInfoNonLive[0]).NumField() != 3 { + t.Error("BitfinexGetAccountInfo struct change/or updated") + } + if reflect.TypeOf(accountInfoNonLive[0].MakerFees).String() != "string" { + t.Error("Bitfinex GetAccountInfo.MakerFees is not a string") + } + if reflect.TypeOf(accountInfoNonLive[0].TakerFees).String() != "string" { + t.Error("Bitfinex GetAccountInfo.TakerFees is not a string") + } + + for _, explicitAI := range accountInfoNonLive { + makerFees, err := strconv.ParseFloat(explicitAI.MakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.MakerFees into float64") + } + if makerFees < 0 { + t.Error("Bitfinex GetAccountInfo.MakerFees is negative") + } + + takerFees, err := strconv.ParseFloat(explicitAI.TakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.TakerFees into float64") + } + if takerFees < 0 { + t.Error("Bitfinex GetAccountInfo.TakerFees is negative") + } + if len(explicitAI.Fees) != 1 { + t.Error("Bitfinex GetAccountInfo.Fees.Pairs incorrect length") + } + + for _, fees := range explicitAI.Fees { + MakerFees, err := strconv.ParseFloat(fees.MakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.Fees.MakerFees into float64") + } + if MakerFees < 0 { + t.Error("Bitfinex GetAccountInfo.Fees.MakerFees is negative") + } + TakerFees, err := strconv.ParseFloat(fees.TakerFees, 64) + if err != nil { + t.Error("Cannot convert Bitfinex GetAccountInfo.Fees.TakerFees into float64") + } + if TakerFees < 0 { + t.Error("Bitfinex GetAccountInfo.Fees.TakerFees is negative") + } + } + } + } +} + +//Hybrid Testing -- TestBitfinexNewDeposit() +func TestBitfinexNewDeposit(t *testing.T) { //Needs attention + t.Parallel() + + applicableMethods := []string{ + "bitcoin_address", + "litecoin_address", + "ethereum_address", + "mastercoin_address", //Requires verified account + "ethereumc_address", + "zcash_address", + "monero_address", + } + expectedCryptoCurrencies := []string{ + "btc", + "ltc", + "eth", + "etc", + "zec", + "xmr", + "dsh", + } + + if ACCOUNT_LIVE_TEST { //Live Test + BitfinexNewDeposit := Bitfinex{} + liveResponse, err := BitfinexNewDeposit.NewDeposit("bitcoin", "deposit", 0) + if err != nil { + t.Error("BitfinexNewDeposit init error: ", err) + } + + if reflect.ValueOf(liveResponse).NumField() != 4 { + t.Error("TestBitfinexNewDeposit struct change/or updated") + } + if reflect.TypeOf(liveResponse.Address).String() != "string" { + t.Error("Bitfinex NewDeposit.Address is not a string") + } + if reflect.TypeOf(liveResponse.Currency).String() != "string" { + t.Error("Bitfinex NewDeposit.Currency is not a string") + } + if reflect.TypeOf(liveResponse.Method).String() != "string" { + t.Error("Bitfinex NewDeposit.Method) is not a string") + } + if reflect.TypeOf(liveResponse.Result).String() != "string" { + t.Error("Bitfinex NewDeposit.Result is not a string") + } + + if len(liveResponse.Address) != 34 { + t.Error("Bitfinex NewDeposit.Address is incorrect") + } + if !DataContains(expectedCryptoCurrencies, liveResponse.Currency) { + t.Error("Bitfinex NewDeposit.Currency currency mismatch" + liveResponse.Currency) + } + if !DataContains(applicableMethods, liveResponse.Method) { + t.Error("Bitfinex NewDeposit.Method method mismatch") + } + if liveResponse.Result != "" && liveResponse.Result != "success" { + t.Error("Bitfinex NewDeposit.Result " + liveResponse.Result) + } + + } else { //Non-Live Test + nonLiveResponse := BitfinexDepositResponse{} + nonLiveResponse.Address = "1DPUgBaZoKbL38BEC1A3exPKCDZjQpnBa1" + nonLiveResponse.Currency = "btc" + nonLiveResponse.Method = "bitcoin_address" + nonLiveResponse.Result = "" + + if reflect.ValueOf(nonLiveResponse).NumField() != 4 { + t.Error("TestBitfinexNewDeposit struct change/or updated") + } + if reflect.TypeOf(nonLiveResponse.Address).String() != "string" { + t.Error("Bitfinex NewDeposit.Address is not a string") + } + if reflect.TypeOf(nonLiveResponse.Currency).String() != "string" { + t.Error("Bitfinex NewDeposit.Currency is not a string") + } + if reflect.TypeOf(nonLiveResponse.Method).String() != "string" { + t.Error("Bitfinex NewDeposit.Method) is not a string") + } + if reflect.TypeOf(nonLiveResponse.Result).String() != "string" { + t.Error("Bitfinex NewDeposit.Result is not a string") + } + + if len(nonLiveResponse.Address) != 34 { + t.Error("Bitfinex NewDeposit.Address is incorrect") + } + if !DataContains(expectedCryptoCurrencies, nonLiveResponse.Currency) { + t.Error("Bitfinex NewDeposit.Currency currency mismatch") + } + if !DataContains(applicableMethods, nonLiveResponse.Method) { + t.Error("Bitfinex NewDeposit.Method method mismatch") + } + if nonLiveResponse.Result != "" && nonLiveResponse.Result != "success" { + t.Error("Bitfinex NewDeposit.Result " + nonLiveResponse.Result) + } + } +} + +//Non-Live Testing -- TestBitfinexNewOrder() +func TestBitfinexNewOrder(t *testing.T) { + t.Parallel() + + BitfinexNewOrder := Bitfinex{} + if ACCOUNT_LIVE_TEST { + liveResponse, err := BitfinexNewOrder.NewOrder("BTCUSD", 0.0, 0.0, true, "test", false) + if err != nil { + log.Println("TestBitfinexNewOrder", err) + } + log.Println(liveResponse) + } + + nonLiveResponse := BitfinexOrder{} + nonLiveResponse.AverageExecutionPrice = "0.0" + nonLiveResponse.Exchange = "bitfinex" + nonLiveResponse.ExecutedAmount = "0.0" + nonLiveResponse.ID = 448364249 + nonLiveResponse.IsCancelled = false + nonLiveResponse.IsHidden = false + nonLiveResponse.IsLive = true + nonLiveResponse.OrderID = 448364249 + nonLiveResponse.OriginalAmount = "0.01" + nonLiveResponse.Price = "0.01" + nonLiveResponse.RemainingAmount = "0.01" + nonLiveResponse.Side = "buy" + nonLiveResponse.Symbol = "btcusd" + nonLiveResponse.Timestamp = "1444272165.252370982" + nonLiveResponse.Type = "exchange limit" + nonLiveResponse.WasForced = false + + if reflect.ValueOf(nonLiveResponse).NumField() != 16 { + t.Error("TestBitfinexNewDeposit struct change/or updated") + } + if reflect.TypeOf(nonLiveResponse.AverageExecutionPrice).String() != "string" { + t.Error("Bitfinex NewOrder.Address is not a string") + } + if reflect.TypeOf(nonLiveResponse.Exchange).String() != "string" { + t.Error("Bitfinex NewOrder.Exchange is not a string") + } + if reflect.TypeOf(nonLiveResponse.ExecutedAmount).String() != "string" { + t.Error("Bitfinex NewOrder.ExecutedAmount is not a string") + } + if reflect.TypeOf(nonLiveResponse.OrderID).String() != "int64" { + t.Error("Bitfinex NewOrder.ID is not an int64") + } + if reflect.TypeOf(nonLiveResponse.IsCancelled).String() != "bool" { + t.Error("Bitfinex NewOrder.IsCancelled is not a bool") + } + if reflect.TypeOf(nonLiveResponse.IsHidden).String() != "bool" { + t.Error("Bitfinex NewOrder.IsHidden is not a bool") + } + if reflect.TypeOf(nonLiveResponse.IsLive).String() != "bool" { + t.Error("Bitfinex NewOrder.IsLive is not a bool") + } + if reflect.TypeOf(nonLiveResponse.OrderID).String() != "int64" { + t.Error("Bitfinex NewOrder.OrderID is not an int64") + } + if reflect.TypeOf(nonLiveResponse.OriginalAmount).String() != "string" { + t.Error("Bitfinex NewOrder.OriginalAmount is not a string") + } + if reflect.TypeOf(nonLiveResponse.Price).String() != "string" { + t.Error("Bitfinex NewOrder.Price is not a string") + } + if reflect.TypeOf(nonLiveResponse.RemainingAmount).String() != "string" { + t.Error("Bitfinex NewOrder.RemainingAmount is not a string") + } + if reflect.TypeOf(nonLiveResponse.Side).String() != "string" { + t.Error("Bitfinex NewOrder.Side is not a string") + } + if reflect.TypeOf(nonLiveResponse.Symbol).String() != "string" { + t.Error("Bitfinex NewOrder.Address is not a string") + } + if reflect.TypeOf(nonLiveResponse.Timestamp).String() != "string" { + t.Error("Bitfinex NewOrder.Timestamp is not a string") + } + if reflect.TypeOf(nonLiveResponse.Type).String() != "string" { + t.Error("Bitfinex NewOrder.Type is not a string") + } + if reflect.TypeOf(nonLiveResponse.WasForced).String() != "bool" { + t.Error("Bitfinex NewOrder.WasForced is not a bool") + } + + averageExecutionPrice, err := strconv.ParseFloat(nonLiveResponse.AverageExecutionPrice, 64) + if err != nil { + t.Error("Bitfinex NewOrder.AverageExecutionPrice cannot convert to float64") + } + if averageExecutionPrice < 0 { + t.Error("Bitfinex NewOrder.AverageExecutionPrice is negative") + } + if nonLiveResponse.Exchange != "bitfinex" { + t.Error("Bitfinex NewOrder.AverageExecutionPrice wrong exchange name") + } + executedAmount, err := strconv.ParseFloat(nonLiveResponse.ExecutedAmount, 64) + if err != nil { + t.Error("Bitfinex NewOrder.ExecutedAmount cannot convert to float64") + } + if executedAmount < 0 { + t.Error("Bitfinex NewOrder.ExecutedAmount is negative or 0") + } + if nonLiveResponse.ID <= 0 { + t.Error("Bitfinex NewOrder.ID is negative or 0") + } + if nonLiveResponse.OrderID <= 0 { + t.Error("Bitfinex NewOrder.OrderID is negative or 0") + } + originalAmount, err := strconv.ParseFloat(nonLiveResponse.OriginalAmount, 64) + if err != nil { + t.Error("Bitfinex NewOrder.OriginalAmount cannot convert to float64") + } + if originalAmount <= 0 { + t.Error("Bitfinex NewOrder.OriginalAmount is negative or 0") + } + price, err := strconv.ParseFloat(nonLiveResponse.Price, 64) + if err != nil { + t.Error("Bitfinex NewOrder.Price cannot convert to float64") + } + if price <= 0 { + t.Error("Bitfinex NewOrder.Price is negative or 0") + } + remainingAmount, err := strconv.ParseFloat(nonLiveResponse.RemainingAmount, 64) + if err != nil { + t.Error("Bitfinex NewOrder.RemainingAmount cannot convert to float64") + } + if remainingAmount <= 0 { + t.Error("Bitfinex NewOrder.RemainingAmount is negative or 0") + } + nonLiveTimestamp, err := strconv.ParseFloat(nonLiveResponse.Timestamp, 64) + if err != nil { + t.Error("Bitfinex NewOrder.Timestamp cannot convert to float64") + } + if nonLiveTimestamp <= 0 { + t.Error("Bitfinex NewOrder.Timestamp is negative or 0") + } +} + +//Non-Live Testing -- TestBitfinexNewOrderMulti() +func TestBitfinexNewOrderMulti(t *testing.T) { + t.Parallel() + + BitfinexNewOrderMulti := Bitfinex{} + var orders []BitfinexPlaceOrder + order := BitfinexPlaceOrder{} + order.Amount = 0.0 + order.Exchange = "bitfinex" + order.Price = 0.0 + order.Side = "test" + order.Symbol = "BTCUSD" + order.Type = "test" + orders = append(orders, order) + + if ACCOUNT_LIVE_TEST { + response, err := BitfinexNewOrderMulti.NewOrderMulti(orders) + if err != nil { + log.Println("TestBitfinexNewOrderMulti", err, "\nResponse: ", response, "\n") + } + } + + nonLiveResponse := BitfinexOrderMultiResponse{} + nonLiveResponse.Status = "success" + + orderTest := BitfinexOrder{} + orderTest.AverageExecutionPrice = "0.0" + orderTest.Exchange = "bitfinex" + orderTest.ExecutedAmount = "0.0" + orderTest.ID = 448364249 + orderTest.IsCancelled = false + orderTest.IsHidden = false + orderTest.IsLive = true + orderTest.OrderID = 448364249 + orderTest.OriginalAmount = "0.01" + orderTest.Price = "0.01" + orderTest.RemainingAmount = "0.01" + orderTest.Side = "buy" + orderTest.Symbol = "btcusd" + orderTest.Timestamp = "1444272165.252370982" + orderTest.Type = "exchange limit" + orderTest.WasForced = false + + nonLiveResponse.Orders = append(nonLiveResponse.Orders, orderTest) + + if reflect.ValueOf(nonLiveResponse).NumField() != 2 { + t.Error("TestBitfinexNewOrderMulti struct change/or updated") + } + if reflect.TypeOf(nonLiveResponse.Status).String() != "string" { + t.Error("Bitfinex NewOrderMulti.Status is not a string") + } + if reflect.ValueOf(nonLiveResponse.Orders[0]).NumField() != 16 { + t.Error("TestBitfinexNewOrderMulti struct change/or updated") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].AverageExecutionPrice).String() != "string" { + t.Error("Bitfinex NewOrder.Address is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].Exchange).String() != "string" { + t.Error("Bitfinex NewOrder.Exchange is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].ExecutedAmount).String() != "string" { + t.Error("Bitfinex NewOrder.ExecutedAmount is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].OrderID).String() != "int64" { + t.Error("Bitfinex NewOrder.ID is not an int64") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].IsCancelled).String() != "bool" { + t.Error("Bitfinex NewOrder.IsCancelled is not a bool") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].IsHidden).String() != "bool" { + t.Error("Bitfinex NewOrder.IsHidden is not a bool") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].IsLive).String() != "bool" { + t.Error("Bitfinex NewOrder.IsLive is not a bool") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].OrderID).String() != "int64" { + t.Error("Bitfinex NewOrder.OrderID is not an int64") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].OriginalAmount).String() != "string" { + t.Error("Bitfinex NewOrder.OriginalAmount is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].Price).String() != "string" { + t.Error("Bitfinex NewOrder.Price is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].RemainingAmount).String() != "string" { + t.Error("Bitfinex NewOrder.RemainingAmount is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].Side).String() != "string" { + t.Error("Bitfinex NewOrder.Side is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].Symbol).String() != "string" { + t.Error("Bitfinex NewOrder.Address is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].Timestamp).String() != "string" { + t.Error("Bitfinex NewOrder.Timestamp is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].Type).String() != "string" { + t.Error("Bitfinex NewOrder.Type is not a string") + } + if reflect.TypeOf(nonLiveResponse.Orders[0].WasForced).String() != "bool" { + t.Error("Bitfinex NewOrder.WasForced is not a bool") + } +} diff --git a/main.go b/main.go index 3aba0a7b..93872c9a 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + // "github.com/gorilla/mux" "log" "net/http" "os" From 6e2464fb58d43d06b9628bc8121ed04ca08e39f9 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 1 Apr 2017 14:25:39 +1100 Subject: [PATCH 02/37] refactor - import common.go --- exchanges/bitfinex/bitfinex_test.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/exchanges/bitfinex/bitfinex_test.go b/exchanges/bitfinex/bitfinex_test.go index d4f0bf12..bdf19a8f 100644 --- a/exchanges/bitfinex/bitfinex_test.go +++ b/exchanges/bitfinex/bitfinex_test.go @@ -6,6 +6,8 @@ import ( "reflect" "strconv" "testing" + + "github.com/thrasher-/gocryptotrader/common" ) var ACCOUNT_LIVE_TEST bool = true @@ -532,7 +534,7 @@ func TestBitfinexGetAccountInfo(t *testing.T) { } if len(expectedCryptoCurrencies) == len(accountInfoLive[0].Fees) { - if !DataContains(expectedCryptoCurrencies, accountInfoLive[0].Fees[0].Pairs) { + if !common.DataContains(expectedCryptoCurrencies, accountInfoLive[0].Fees[0].Pairs) { t.Error("Bitfinex GetAccountInfo currency mismatch") } } else if len(expectedCryptoCurrencies) > len(accountInfoLive[0].Fees) { @@ -694,10 +696,10 @@ func TestBitfinexNewDeposit(t *testing.T) { //Needs attention if len(liveResponse.Address) != 34 { t.Error("Bitfinex NewDeposit.Address is incorrect") } - if !DataContains(expectedCryptoCurrencies, liveResponse.Currency) { + if !common.DataContains(expectedCryptoCurrencies, liveResponse.Currency) { t.Error("Bitfinex NewDeposit.Currency currency mismatch" + liveResponse.Currency) } - if !DataContains(applicableMethods, liveResponse.Method) { + if !common.DataContains(applicableMethods, liveResponse.Method) { t.Error("Bitfinex NewDeposit.Method method mismatch") } if liveResponse.Result != "" && liveResponse.Result != "success" { @@ -730,10 +732,10 @@ func TestBitfinexNewDeposit(t *testing.T) { //Needs attention if len(nonLiveResponse.Address) != 34 { t.Error("Bitfinex NewDeposit.Address is incorrect") } - if !DataContains(expectedCryptoCurrencies, nonLiveResponse.Currency) { + if !common.DataContains(expectedCryptoCurrencies, nonLiveResponse.Currency) { t.Error("Bitfinex NewDeposit.Currency currency mismatch") } - if !DataContains(applicableMethods, nonLiveResponse.Method) { + if !common.DataContains(applicableMethods, nonLiveResponse.Method) { t.Error("Bitfinex NewDeposit.Method method mismatch") } if nonLiveResponse.Result != "" && nonLiveResponse.Result != "success" { From 3636d474d6b5a1fd73d37e03d37b92896e1afc2c Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 1 Apr 2017 14:35:56 +1100 Subject: [PATCH 03/37] conform to BitfinexOrder struct types --- exchanges/bitfinex/bitfinex_test.go | 50 +++++++++-------------------- 1 file changed, 15 insertions(+), 35 deletions(-) diff --git a/exchanges/bitfinex/bitfinex_test.go b/exchanges/bitfinex/bitfinex_test.go index bdf19a8f..757b8afc 100644 --- a/exchanges/bitfinex/bitfinex_test.go +++ b/exchanges/bitfinex/bitfinex_test.go @@ -758,17 +758,17 @@ func TestBitfinexNewOrder(t *testing.T) { } nonLiveResponse := BitfinexOrder{} - nonLiveResponse.AverageExecutionPrice = "0.0" + nonLiveResponse.AverageExecutionPrice = 0.0 nonLiveResponse.Exchange = "bitfinex" - nonLiveResponse.ExecutedAmount = "0.0" + nonLiveResponse.ExecutedAmount = 0.0 nonLiveResponse.ID = 448364249 nonLiveResponse.IsCancelled = false nonLiveResponse.IsHidden = false nonLiveResponse.IsLive = true nonLiveResponse.OrderID = 448364249 - nonLiveResponse.OriginalAmount = "0.01" - nonLiveResponse.Price = "0.01" - nonLiveResponse.RemainingAmount = "0.01" + nonLiveResponse.OriginalAmount = 0.01 + nonLiveResponse.Price = 0.01 + nonLiveResponse.RemainingAmount = 0.01 nonLiveResponse.Side = "buy" nonLiveResponse.Symbol = "btcusd" nonLiveResponse.Timestamp = "1444272165.252370982" @@ -827,21 +827,13 @@ func TestBitfinexNewOrder(t *testing.T) { t.Error("Bitfinex NewOrder.WasForced is not a bool") } - averageExecutionPrice, err := strconv.ParseFloat(nonLiveResponse.AverageExecutionPrice, 64) - if err != nil { - t.Error("Bitfinex NewOrder.AverageExecutionPrice cannot convert to float64") - } - if averageExecutionPrice < 0 { + if nonLiveResponse.AverageExecutionPrice < 0 { t.Error("Bitfinex NewOrder.AverageExecutionPrice is negative") } if nonLiveResponse.Exchange != "bitfinex" { t.Error("Bitfinex NewOrder.AverageExecutionPrice wrong exchange name") } - executedAmount, err := strconv.ParseFloat(nonLiveResponse.ExecutedAmount, 64) - if err != nil { - t.Error("Bitfinex NewOrder.ExecutedAmount cannot convert to float64") - } - if executedAmount < 0 { + if nonLiveResponse.ExecutedAmount < 0 { t.Error("Bitfinex NewOrder.ExecutedAmount is negative or 0") } if nonLiveResponse.ID <= 0 { @@ -850,25 +842,13 @@ func TestBitfinexNewOrder(t *testing.T) { if nonLiveResponse.OrderID <= 0 { t.Error("Bitfinex NewOrder.OrderID is negative or 0") } - originalAmount, err := strconv.ParseFloat(nonLiveResponse.OriginalAmount, 64) - if err != nil { - t.Error("Bitfinex NewOrder.OriginalAmount cannot convert to float64") - } - if originalAmount <= 0 { + if nonLiveResponse.OriginalAmount <= 0 { t.Error("Bitfinex NewOrder.OriginalAmount is negative or 0") } - price, err := strconv.ParseFloat(nonLiveResponse.Price, 64) - if err != nil { - t.Error("Bitfinex NewOrder.Price cannot convert to float64") - } - if price <= 0 { + if nonLiveResponse.Price <= 0 { t.Error("Bitfinex NewOrder.Price is negative or 0") } - remainingAmount, err := strconv.ParseFloat(nonLiveResponse.RemainingAmount, 64) - if err != nil { - t.Error("Bitfinex NewOrder.RemainingAmount cannot convert to float64") - } - if remainingAmount <= 0 { + if nonLiveResponse.RemainingAmount <= 0 { t.Error("Bitfinex NewOrder.RemainingAmount is negative or 0") } nonLiveTimestamp, err := strconv.ParseFloat(nonLiveResponse.Timestamp, 64) @@ -906,17 +886,17 @@ func TestBitfinexNewOrderMulti(t *testing.T) { nonLiveResponse.Status = "success" orderTest := BitfinexOrder{} - orderTest.AverageExecutionPrice = "0.0" + orderTest.AverageExecutionPrice = 0.0 orderTest.Exchange = "bitfinex" - orderTest.ExecutedAmount = "0.0" + orderTest.ExecutedAmount = 0.0 orderTest.ID = 448364249 orderTest.IsCancelled = false orderTest.IsHidden = false orderTest.IsLive = true orderTest.OrderID = 448364249 - orderTest.OriginalAmount = "0.01" - orderTest.Price = "0.01" - orderTest.RemainingAmount = "0.01" + orderTest.OriginalAmount = 0.01 + orderTest.Price = 0.01 + orderTest.RemainingAmount = 0.01 orderTest.Side = "buy" orderTest.Symbol = "btcusd" orderTest.Timestamp = "1444272165.252370982" From 03aca795848da67c86c0ad1be219ed139cd44277 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 1 Apr 2017 15:22:10 +1100 Subject: [PATCH 04/37] Updated Non-live & live test support --- exchanges/bitfinex/bitfinex_test.go | 102 +++++++++++++++------------- 1 file changed, 53 insertions(+), 49 deletions(-) diff --git a/exchanges/bitfinex/bitfinex_test.go b/exchanges/bitfinex/bitfinex_test.go index 757b8afc..725f8573 100644 --- a/exchanges/bitfinex/bitfinex_test.go +++ b/exchanges/bitfinex/bitfinex_test.go @@ -1,7 +1,7 @@ package bitfinex import ( - "log" + "fmt" "net/url" "reflect" "strconv" @@ -10,7 +10,7 @@ import ( "github.com/thrasher-/gocryptotrader/common" ) -var ACCOUNT_LIVE_TEST bool = true +var ACCOUNT_LIVE_TEST bool = false //Live Testing -- TestBitfinexGetTicker() func TestBitfinexGetTicker(t *testing.T) { @@ -519,35 +519,38 @@ func TestBitfinexGetAccountInfo(t *testing.T) { if ACCOUNT_LIVE_TEST { //Live Test BitfinexGetAccountInfo := Bitfinex{} - accountInfoLive, err := BitfinexGetAccountInfo.GetAccountInfo() + response, err := BitfinexGetAccountInfo.GetAccountInfo() if err != nil { - t.Error("BitfinexGetAccountInfo init error: ", err) + newErrString := fmt.Sprintf("TestBitfinexGetAccountInfo: \nError: %s\n", err) + t.Error(newErrString) + response = append(response, BitfinexAccountInfo{}) } - if reflect.ValueOf(accountInfoLive[0]).NumField() != 3 { + + if reflect.ValueOf(response[0]).NumField() != 3 { t.Error("BitfinexGetAccountInfo struct change/or updated") } - if reflect.TypeOf(accountInfoLive[0].MakerFees).String() != "string" { + if reflect.TypeOf(response[0].MakerFees).String() != "string" { t.Error("Bitfinex GetAccountInfo.MakerFees is not a string") } - if reflect.TypeOf(accountInfoLive[0].TakerFees).String() != "string" { + if reflect.TypeOf(response[0].TakerFees).String() != "string" { t.Error("Bitfinex GetAccountInfo.TakerFees is not a string") } - if len(expectedCryptoCurrencies) == len(accountInfoLive[0].Fees) { - if !common.DataContains(expectedCryptoCurrencies, accountInfoLive[0].Fees[0].Pairs) { + if len(expectedCryptoCurrencies) == len(response[0].Fees) { + if !common.DataContains(expectedCryptoCurrencies, response[0].Fees[0].Pairs) { t.Error("Bitfinex GetAccountInfo currency mismatch") } - } else if len(expectedCryptoCurrencies) > len(accountInfoLive[0].Fees) { + } else if len(expectedCryptoCurrencies) > len(response[0].Fees) { t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies > Exchange Currencies") } else { t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies < Exchange Currencies") } - if len(accountInfoLive[0].Fees) != 7 { + if len(response[0].Fees) != 7 { t.Error("Bitfinex GetAccountInfo.Fees incorrect length") } - for _, explicitAI := range accountInfoLive { + for _, explicitAI := range response { makerFees, err := strconv.ParseFloat(explicitAI.MakerFees, 64) if err != nil { t.Error("Cannot convert Bitfinex GetAccountInfo.MakerFees into float64") @@ -750,11 +753,11 @@ func TestBitfinexNewOrder(t *testing.T) { BitfinexNewOrder := Bitfinex{} if ACCOUNT_LIVE_TEST { - liveResponse, err := BitfinexNewOrder.NewOrder("BTCUSD", 0.0, 0.0, true, "test", false) + response, err := BitfinexNewOrder.NewOrder("BTCUSD", 0.0, 0.0, true, "test", false) if err != nil { - log.Println("TestBitfinexNewOrder", err) + newErrString := fmt.Sprintf("TestBitfinexNewOrder: \nError: %s\nIs_live: %t\n", err, response.IsLive) + t.Error(newErrString) } - log.Println(liveResponse) } nonLiveResponse := BitfinexOrder{} @@ -778,14 +781,14 @@ func TestBitfinexNewOrder(t *testing.T) { if reflect.ValueOf(nonLiveResponse).NumField() != 16 { t.Error("TestBitfinexNewDeposit struct change/or updated") } - if reflect.TypeOf(nonLiveResponse.AverageExecutionPrice).String() != "string" { - t.Error("Bitfinex NewOrder.Address is not a string") + if reflect.TypeOf(nonLiveResponse.AverageExecutionPrice).String() != "float64" { + t.Error("Bitfinex NewOrder.AverageExecutionPrice is not a float64") } if reflect.TypeOf(nonLiveResponse.Exchange).String() != "string" { t.Error("Bitfinex NewOrder.Exchange is not a string") } - if reflect.TypeOf(nonLiveResponse.ExecutedAmount).String() != "string" { - t.Error("Bitfinex NewOrder.ExecutedAmount is not a string") + if reflect.TypeOf(nonLiveResponse.ExecutedAmount).String() != "float64" { + t.Error("Bitfinex NewOrder.ExecutedAmount is not a float64") } if reflect.TypeOf(nonLiveResponse.OrderID).String() != "int64" { t.Error("Bitfinex NewOrder.ID is not an int64") @@ -802,14 +805,14 @@ func TestBitfinexNewOrder(t *testing.T) { if reflect.TypeOf(nonLiveResponse.OrderID).String() != "int64" { t.Error("Bitfinex NewOrder.OrderID is not an int64") } - if reflect.TypeOf(nonLiveResponse.OriginalAmount).String() != "string" { - t.Error("Bitfinex NewOrder.OriginalAmount is not a string") + if reflect.TypeOf(nonLiveResponse.OriginalAmount).String() != "float64" { + t.Error("Bitfinex NewOrder.OriginalAmount is not a float64") } - if reflect.TypeOf(nonLiveResponse.Price).String() != "string" { - t.Error("Bitfinex NewOrder.Price is not a string") + if reflect.TypeOf(nonLiveResponse.Price).String() != "float64" { + t.Error("Bitfinex NewOrder.Price is not a float64") } - if reflect.TypeOf(nonLiveResponse.RemainingAmount).String() != "string" { - t.Error("Bitfinex NewOrder.RemainingAmount is not a string") + if reflect.TypeOf(nonLiveResponse.RemainingAmount).String() != "float64" { + t.Error("Bitfinex NewOrder.RemainingAmount is not a float64") } if reflect.TypeOf(nonLiveResponse.Side).String() != "string" { t.Error("Bitfinex NewOrder.Side is not a string") @@ -878,7 +881,8 @@ func TestBitfinexNewOrderMulti(t *testing.T) { if ACCOUNT_LIVE_TEST { response, err := BitfinexNewOrderMulti.NewOrderMulti(orders) if err != nil { - log.Println("TestBitfinexNewOrderMulti", err, "\nResponse: ", response, "\n") + newErrString := fmt.Sprintf("TestBitfinexNewOrderMulti: \nError: %s\n Status: %s\n", err, response.Status) + t.Error(newErrString) } } @@ -906,60 +910,60 @@ func TestBitfinexNewOrderMulti(t *testing.T) { nonLiveResponse.Orders = append(nonLiveResponse.Orders, orderTest) if reflect.ValueOf(nonLiveResponse).NumField() != 2 { - t.Error("TestBitfinexNewOrderMulti struct change/or updated") + t.Error("Bitfinex NewOrderMulti struct change/or updated") } if reflect.TypeOf(nonLiveResponse.Status).String() != "string" { t.Error("Bitfinex NewOrderMulti.Status is not a string") } if reflect.ValueOf(nonLiveResponse.Orders[0]).NumField() != 16 { - t.Error("TestBitfinexNewOrderMulti struct change/or updated") + t.Error("Bitfinex NewOrderMulti struct change/or updated") } - if reflect.TypeOf(nonLiveResponse.Orders[0].AverageExecutionPrice).String() != "string" { - t.Error("Bitfinex NewOrder.Address is not a string") + if reflect.TypeOf(nonLiveResponse.Orders[0].AverageExecutionPrice).String() != "float64" { + t.Error("Bitfinex NewOrderMulti.AverageExecutionPrice is not a float64") } if reflect.TypeOf(nonLiveResponse.Orders[0].Exchange).String() != "string" { - t.Error("Bitfinex NewOrder.Exchange is not a string") + t.Error("Bitfinex NewOrderMulti.Exchange is not a string") } - if reflect.TypeOf(nonLiveResponse.Orders[0].ExecutedAmount).String() != "string" { - t.Error("Bitfinex NewOrder.ExecutedAmount is not a string") + if reflect.TypeOf(nonLiveResponse.Orders[0].ExecutedAmount).String() != "float64" { + t.Error("Bitfinex NewOrderMulti.ExecutedAmount is not a float64") } if reflect.TypeOf(nonLiveResponse.Orders[0].OrderID).String() != "int64" { - t.Error("Bitfinex NewOrder.ID is not an int64") + t.Error("Bitfinex NewOrderMulti.ID is not an int64") } if reflect.TypeOf(nonLiveResponse.Orders[0].IsCancelled).String() != "bool" { - t.Error("Bitfinex NewOrder.IsCancelled is not a bool") + t.Error("Bitfinex NewOrderMulti.IsCancelled is not a bool") } if reflect.TypeOf(nonLiveResponse.Orders[0].IsHidden).String() != "bool" { - t.Error("Bitfinex NewOrder.IsHidden is not a bool") + t.Error("Bitfinex NewOrderMulti.IsHidden is not a bool") } if reflect.TypeOf(nonLiveResponse.Orders[0].IsLive).String() != "bool" { - t.Error("Bitfinex NewOrder.IsLive is not a bool") + t.Error("Bitfinex NewOrderMulti.IsLive is not a bool") } if reflect.TypeOf(nonLiveResponse.Orders[0].OrderID).String() != "int64" { - t.Error("Bitfinex NewOrder.OrderID is not an int64") + t.Error("Bitfinex NewOrderMulti.OrderID is not an int64") } - if reflect.TypeOf(nonLiveResponse.Orders[0].OriginalAmount).String() != "string" { - t.Error("Bitfinex NewOrder.OriginalAmount is not a string") + if reflect.TypeOf(nonLiveResponse.Orders[0].OriginalAmount).String() != "float64" { + t.Error("Bitfinex NewOrderMulti.OriginalAmount is not a float64") } - if reflect.TypeOf(nonLiveResponse.Orders[0].Price).String() != "string" { - t.Error("Bitfinex NewOrder.Price is not a string") + if reflect.TypeOf(nonLiveResponse.Orders[0].Price).String() != "float64" { + t.Error("Bitfinex NewOrderMulti.Price is not a float64") } - if reflect.TypeOf(nonLiveResponse.Orders[0].RemainingAmount).String() != "string" { - t.Error("Bitfinex NewOrder.RemainingAmount is not a string") + if reflect.TypeOf(nonLiveResponse.Orders[0].RemainingAmount).String() != "float64" { + t.Error("Bitfinex NewOrderMulti.RemainingAmount is not a float64") } if reflect.TypeOf(nonLiveResponse.Orders[0].Side).String() != "string" { - t.Error("Bitfinex NewOrder.Side is not a string") + t.Error("Bitfinex NewOrderMulti.Side is not a string") } if reflect.TypeOf(nonLiveResponse.Orders[0].Symbol).String() != "string" { - t.Error("Bitfinex NewOrder.Address is not a string") + t.Error("Bitfinex NewOrderMulti.Address is not a string") } if reflect.TypeOf(nonLiveResponse.Orders[0].Timestamp).String() != "string" { - t.Error("Bitfinex NewOrder.Timestamp is not a string") + t.Error("Bitfinex NewOrderMulti.Timestamp is not a string") } if reflect.TypeOf(nonLiveResponse.Orders[0].Type).String() != "string" { - t.Error("Bitfinex NewOrder.Type is not a string") + t.Error("Bitfinex NewOrderMulti.Type is not a string") } if reflect.TypeOf(nonLiveResponse.Orders[0].WasForced).String() != "bool" { - t.Error("Bitfinex NewOrder.WasForced is not a bool") + t.Error("Bitfinex NewOrderMulti.WasForced is not a bool") } } From 58741e73ef92c33f2fc2317a55287c0fd23129a5 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 1 Apr 2017 15:32:43 +1100 Subject: [PATCH 05/37] Added test for DataContains function in common.go --- common/common_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/common/common_test.go b/common/common_test.go index 4ef592ff..d00c5700 100644 --- a/common/common_test.go +++ b/common/common_test.go @@ -129,6 +129,23 @@ func TestStringContains(t *testing.T) { } } +func TestDataContains(t *testing.T) { + t.Parallel() + originalHaystack := []string{"hello", "world", "data", "Contains", "string"} + originalNeedle := "world" + anotherNeedle := "thing" + expectedOutput := true + expectedOutputTwo := false + actualResult := DataContains(originalHaystack, originalNeedle) + if actualResult != expectedOutput { + t.Error(fmt.Sprintf("Test failed. Expected '%t'. Actual '%t'", expectedOutput, actualResult)) + } + actualResult = DataContains(originalHaystack, anotherNeedle) + if actualResult != expectedOutputTwo { + t.Error(fmt.Sprintf("Test failed. Expected '%t'. Actual '%t'", expectedOutputTwo, actualResult)) + } +} + func TestJoinStrings(t *testing.T) { t.Parallel() originalInputOne := []string{"hello", "moto"} From e27260df6b1aed508a25bad893369a37bb4da2bd Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 1 Apr 2017 20:38:53 +1100 Subject: [PATCH 06/37] Added basic error handling for RetrieveConfigCurrencyPairs --- config/config.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index 749859b2..0e873aa4 100644 --- a/config/config.go +++ b/config/config.go @@ -205,10 +205,19 @@ func (c *Config) CheckWebserverConfigValues() error { return nil } -func (c *Config) RetrieveConfigCurrencyPairs() { +func (c *Config) RetrieveConfigCurrencyPairs() error { cryptoCurrencies := common.SplitStrings(c.Cryptocurrencies, ",") fiatCurrencies := common.SplitStrings(currency.DEFAULT_CURRENCIES, ",") + for _, s := range cryptoCurrencies { + _, err := strconv.Atoi(s) + if err != nil && common.StringContains(c.Cryptocurrencies, s) { + continue + } else { + return errors.New("RetrieveConfigCurrencyPairs: Incorrect Crypto-Currency") + } + } + for _, exchange := range c.Exchanges { if exchange.Enabled { baseCurrencies := common.SplitStrings(exchange.BaseCurrencies, ",") @@ -252,6 +261,8 @@ func (c *Config) RetrieveConfigCurrencyPairs() { } c.Cryptocurrencies = common.JoinStrings(cryptoCurrencies, ",") currency.CryptoCurrencies = c.Cryptocurrencies + + return nil } func (c *Config) ReadConfig() error { From 38514eb8ab88dd375340b3f2c57cc041b8a253f2 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 1 Apr 2017 20:42:19 +1100 Subject: [PATCH 07/37] Added test support for config.go --- config/config_tests/config_example.dat | 287 +++++++++++++++++++++++++ config/config_tests/config_test.go | 148 +++++++++++++ 2 files changed, 435 insertions(+) create mode 100644 config/config_tests/config_example.dat create mode 100644 config/config_tests/config_test.go diff --git a/config/config_tests/config_example.dat b/config/config_tests/config_example.dat new file mode 100644 index 00000000..973ffa04 --- /dev/null +++ b/config/config_tests/config_example.dat @@ -0,0 +1,287 @@ +{ + "Name": "Skynet", + "EncryptConfig": 0, + "Cryptocurrencies": "BTC,LTC,ETH,XRP,NMC,NVC,PPC,XBT,DOGE,DASH", + "PortfolioAddresses": { + "Addresses": [ + { + "Address": "1JCe8z4jJVNXSjohjM4i9Hh813dLCNx2Sy", + "CoinType": "BTC", + "Balance": 124178.0002442 + }, + { + "Address": "3Nxwenay9Z8Lc9JBiywExpnEFiLp6Afp8v", + "CoinType": "BTC", + "Balance": 103439.83659727 + }, + { + "Address": "LgY8ahfHRhvjVQC1zJnBhFMG5pCTMuKRqh", + "CoinType": "LTC", + "Balance": 3.00000005e+06 + }, + { + "Address": "0xb794f5ea0ba39494ce839613fffba74279579268", + "CoinType": "ETH", + "Balance": 5.774999820458524e+06 + } + ] + }, + "SMSGlobal": { + "Enabled": false, + "Username": "Username", + "Password": "Password", + "Contacts": [ + { + "Name": "Bob", + "Number": "12345", + "Enabled": false + } + ] + }, + "Webserver": { + "Enabled": false, + "AdminUsername": "admin", + "AdminPassword": "Password", + "ListenAddress": ":9050" + }, + "Exchanges": [ + { + "Name": "ANX", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", + "EnabledPairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", + "BaseCurrencies": "USD,HKD,EUR,CAD,AUD,SGD,JPY,GBP,NZD" + }, + { + "Name": "Bitfinex", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC,ETCBTC,ETCUSD,BFXUSD,BFXBTC,RRTUSD,RRTBTC,ZECUSD,ZECBTC,XMRUSD,XMRBTC,DSHUSD,DSHBTC", + "EnabledPairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC", + "BaseCurrencies": "USD" + }, + { + "Name": "Bitstamp", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "ClientID", + "AvailablePairs": "BTCUSD,BTCEUR,EURUSD,XRPUSD,XRPEUR", + "EnabledPairs": "BTCUSD,BTCEUR,EURUSD,XRPUSD,XRPEUR", + "BaseCurrencies": "USD,EUR" + }, + { + "Name": "BTCC", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCCNY,LTCCNY,LTCBTC", + "EnabledPairs": "BTCCNY,LTCCNY,LTCBTC", + "BaseCurrencies": "CNY" + }, + { + "Name": "BTCE", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", + "EnabledPairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", + "BaseCurrencies": "USD,RUR,EUR" + }, + { + "Name": "BTC Markets", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "LTC,BTC", + "EnabledPairs": "LTC,BTC", + "BaseCurrencies": "AUD" + }, + { + "Name": "GDAX", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "ClientID", + "AvailablePairs": "BTCGBP,BTCEUR,ETHUSD,ETHBTC,LTCUSD,LTCBTC,BTCUSD", + "EnabledPairs": "BTCUSD,BTCGBP,BTCEUR", + "BaseCurrencies": "USD,GBP,EUR" + }, + { + "Name": "Gemini", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,ETHBTC,ETHUSD", + "EnabledPairs": "BTCUSD", + "BaseCurrencies": "USD" + }, + { + "Name": "Huobi", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCCNY,LTCCNY", + "EnabledPairs": "BTCCNY,LTCCNY", + "BaseCurrencies": "CNY" + }, + { + "Name": "ITBIT", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "ClientID", + "AvailablePairs": "XBTUSD,XBTSGD,XBTEUR", + "EnabledPairs": "XBTUSD,XBTSGD,XBTEUR", + "BaseCurrencies": "USD,SGD,EUR" + }, + { + "Name": "Kraken", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "ETCUSD,ICNETH,REPXBT,ZECXBT,ETHXBT,ETHXBT.d,ETHGBP,LTCXBT,XBTGBP.d,XDGXBT,XMRUSD,ZECUSD,ETCETH,ETHJPY,XBTCAD.d,XBTJPY.d,XBTUSD.d,XLMXBT,XLMEUR,XLMUSD,XMREUR,ETCXBT,ETHCAD.d,ETHEUR.d,ETHJPY.d,XBTEUR.d,ETHEUR,ETHGBP.d,ICNXBT,LTCEUR,REPEUR,XBTGBP,XBTJPY,ETHUSD,ETHUSD.d,LTCUSD,REPETH,XBTUSD,XMRXBT,ETCEUR,ETHCAD,REPUSD,XBTCAD,XBTEUR,XRPXBT,ZECEUR", + "EnabledPairs": "ETCUSD,XBTUSD,ETHUSD", + "BaseCurrencies": "EUR,USD,CAD,GBP,JPY" + }, + { + "Name": "LakeBTC", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,BTCEUR,USDHKD,AUDUSD,BTCGBP,BTCNZD,USDJPY,BTCSGD,BTCNGN,EURUSD,USDSGD,NZDUSD,USDNGN,USDCHF,BTCJPY,BTCAUD,BTCCAD,BTCCHF,GBPUSD,USDCAD", + "EnabledPairs": "BTCUSD,BTCAUD", + "BaseCurrencies": "USD,EUR,HKD,AUD,GBP,NZD,JPY,SGD,NGN,CHF,CAD" + }, + { + "Name": "Liqui", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "TIME_BTC,ETH_BTC,GNT_BTC,WAVES_BTC,ICN_BTC,1ST_BTC,WINGS_BTC,MLN_BTC,ROUND_BTC,VSL_BTC,LTC_BTC,DCT_BTC,INCNT_BTC,PLU_BTC,DASH_BTC", + "EnabledPairs": "ETH_BTC,LTC_BTC,DASH_BTC", + "BaseCurrencies": "USD" + }, + { + "Name": "LocalBitcoins", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", + "EnabledPairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", + "BaseCurrencies": "ARS,AUD,BRL,CAD,CHF,CZK,DKK,EUR,GBP,HKD,ILS,INR,MXN,NOK,NZD,PLN,RUB,SEK,SGD,THB,USD,ZAR" + }, + { + "Name": "OKCOIN China", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCCNY,LTCCNY", + "EnabledPairs": "BTCCNY,LTCCNY", + "BaseCurrencies": "CNY" + }, + { + "Name": "OKCOIN International", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,LTCUSD", + "EnabledPairs": "BTCUSD,LTCUSD", + "BaseCurrencies": "USD" + }, + { + "Name": "Poloniex", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTC_XUSD,BTC_FCT,BTC_MMNXT,BTC_NMC,BTC_BITUSD,BTC_RDD,BTC_XMR,BTC_XST,BTC_DSH,BTC_MAID,BTC_DGB,BTC_NEOS,BTC_BLK,BTC_NAUT,BTC_NBT,BTC_XCP,BTC_STR,BTC_BTCD,BTC_GRC,BTC_HUC,BTC_BBR,BTC_XDN,BTC_INDEX,BTC_IOC,BTC_SWARM,BTC_EMC2,BTC_MCN,BTC_NOXT,BTC_MINT,BTC_PTS,BTC_SC,BTC_GEO,BTC_XRP,BTC_FLO,BTC_BITS,BTC_HYP,BTC_XCR,BTC_LTBC,BTC_SYS,BTC_GMC,BTC_ETH,BTC_SYNC,BTC_GAP,BTC_BCN,BTC_C2,BTC_PINK,BTC_FIBRE,BTC_POT,BTC_QTL,BTC_SDC,BTC_XC,BTC_DASH,BTC_SILK,BTC_CLAM,BTC_NAV,BTC_PIGGY,BTC_BCY,BTC_MIL,BTC_XCN,BTC_YACC,BTC_BTS,BTC_QBK,BTC_SJCX,BTC_LQD,BTC_BURST,BTC_RIC,BTC_VRC,BTC_LTC,BTC_XPB,BTC_GRS,BTC_XCH,BTC_ARCH,BTC_QORA,BTC_HZ,BTC_NSR,BTC_XPM,BTC_BITCNY,BTC_EXE,BTC_XMG,BTC_BTC,BTC_BTM,BTC_NOBL,BTC_NXT,BTC_DOGE,BTC_CURE,BTC_MNTA,BTC_ADN,BTC_EXP,BTC_VTC,BTC_FLDC,BTC_MRS,BTC_MYR,BTC_OMNI,BTC_VNL,BTC_USDT,BTC_NOTE,BTC_WDC,BTC_BELA,BTC_VIA,BTC_CGA,BTC_DIEM,BTC_IFC,BTC_XDP,BTC_BLOCK,BTC_MMC,BTC_1CR,BTC_UNITY,BTC_XBC,BTC_GEMZ,BTC_FLT,BTC_PPC,BTC_XEM,BTC_RBY,BTC_CNMT,BTC_ABY,XMR_XDN,XMR_IFC,XMR_DIEM,XMR_BBR,XMR_DSH,XMR_BCN,XMR_LTC,XMR_MAID,XMR_DASH,XMR_BTCD,XMR_HYP,XMR_BLK,XMR_QORA,XMR_MNTA,XMR_NXT,USDT_BTC,USDT_ETH,USDT_XRP,USDT_DASH,USDT_LTC,USDT_NXT,USDT_XMR,USDT_STR", + "EnabledPairs": "BTC_LTC,BTC_ETH,BTC_DOGE,BTC_DASH,BTC_XRP", + "BaseCurrencies": "USD" + } + ] +} \ No newline at end of file diff --git a/config/config_tests/config_test.go b/config/config_tests/config_test.go new file mode 100644 index 00000000..23829c77 --- /dev/null +++ b/config/config_tests/config_test.go @@ -0,0 +1,148 @@ +package test + +import ( + "testing" + + "github.com/thrasher-/gocryptotrader/config" +) + +func TestGetConfigEnabledExchanges(t *testing.T) { + t.Parallel() + + defaultEnabledExchanges := 17 + GetConfigEnabledExchanges := config.GetConfig() + err := GetConfigEnabledExchanges.LoadConfig() + if err != nil { + t.Error("Test failed. GetConfigEnabledExchanges load config error: " + err.Error()) + } + enabledExch := GetConfigEnabledExchanges.GetConfigEnabledExchanges() + if enabledExch != defaultEnabledExchanges { + t.Error("Test failed. GetConfigEnabledExchanges is wrong") + } +} + +func TestGetExchangeConfig(t *testing.T) { + t.Parallel() + + GetExchangeConfig := config.GetConfig() + err := GetExchangeConfig.LoadConfig() + if err != nil { + t.Errorf("Test failed. GetExchangeConfig.LoadConfig Error: %s", err.Error()) + } + r, err := GetExchangeConfig.GetExchangeConfig("ANX") + if err != nil && (config.ExchangeConfig{}) == r { + t.Errorf("Test failed. GetExchangeConfig.GetExchangeConfig Error: %s", err.Error()) + } +} + +func TestUpdateExchangeConfig(t *testing.T) { + t.Parallel() + + UpdateExchangeConfig := config.GetConfig() + err := UpdateExchangeConfig.LoadConfig() + if err != nil { + t.Errorf("Test failed. UpdateExchangeConfig.LoadConfig Error: %s", err.Error()) + } + e, err2 := UpdateExchangeConfig.GetExchangeConfig("ANX") + if err2 != nil { + t.Errorf("Test failed. UpdateExchangeConfig.GetExchangeConfig: %s", err.Error()) + } + e.APIKey = "test1234" + err3 := UpdateExchangeConfig.UpdateExchangeConfig(e) + if err3 != nil { + t.Errorf("Test failed. UpdateExchangeConfig.UpdateExchangeConfig: %s", err.Error()) + } +} + +func TestCheckSMSGlobalConfigValues(t *testing.T) { + t.Parallel() + + checkSMSGlobalConfigValues := config.GetConfig() + err := checkSMSGlobalConfigValues.LoadConfig() + if err != nil { + t.Errorf("Test failed. checkSMSGlobalConfigValues.LoadConfig: %s", err) + } + err2 := checkSMSGlobalConfigValues.CheckSMSGlobalConfigValues() + if err2 == nil { + t.Error("Test failed. checkSMSGlobalConfigValues.CheckSMSGlobalConfigValues: Incorrect Return Value") + } +} + +func TestCheckExchangeConfigValues(t *testing.T) { + t.Parallel() + + checkExchangeConfigValues := config.Config{} + err := checkExchangeConfigValues.LoadConfig() + if err != nil { + t.Errorf("Test failed. checkExchangeConfigValues.LoadConfig: %s", err.Error()) + } + + checkExchangeConfigValues.Exchanges[0].AuthenticatedAPISupport = true + + err3 := checkExchangeConfigValues.CheckExchangeConfigValues() + if err3 != nil { + t.Errorf("Test failed. checkExchangeConfigValues.CheckExchangeConfigValues: %s", err.Error()) + } +} + +func TestCheckWebserverConfigValues(t *testing.T) { + t.Parallel() + + checkWebserverConfigValues := config.GetConfig() + err := checkWebserverConfigValues.LoadConfig() + if err != nil { + t.Errorf("Test failed. checkWebserverConfigValues.LoadConfig: %s", err.Error()) + } + err2 := checkWebserverConfigValues.CheckWebserverConfigValues() + if err2 != nil { + t.Errorf("Test failed. checkWebserverConfigValues.CheckWebserverConfigValues: %s", err2.Error()) + } +} + +func TestRetrieveConfigCurrencyPairs(t *testing.T) { + t.Parallel() + + retrieveConfigCurrencyPairs := config.GetConfig() + err := retrieveConfigCurrencyPairs.LoadConfig() + if err != nil { + t.Errorf("Test failed. checkWebserverConfigValues.LoadConfig: %s", err.Error()) + } + err2 := retrieveConfigCurrencyPairs.RetrieveConfigCurrencyPairs() + if err2 != nil { + t.Errorf("Test failed. checkWebserverConfigValues.RetrieveConfigCurrencyPairs: %s", err2.Error()) + } +} + +func TestReadConfig(t *testing.T) { + t.Parallel() + + readConfig := config.GetConfig() + err := readConfig.ReadConfig() + if err != nil { + t.Error("Test failed. TestReadConfig" + err.Error()) + } +} + +func TestLoadConfig(t *testing.T) { + t.Parallel() + + loadConfig := config.GetConfig() + err := loadConfig.LoadConfig() + if err != nil { + t.Error("Test failed. TestLoadConfig" + err.Error()) + } +} + +func TestSaveConfig(t *testing.T) { + t.Parallel() + + saveConfig := config.GetConfig() + err := saveConfig.LoadConfig() + if err != nil { + t.Errorf("Test failed. TestSaveConfig.LoadConfig: %s", err.Error()) + } + err2 := saveConfig.SaveConfig() + if err2 != nil { + t.Error("Test failed. TestSaveConfig.SaveConfig, %s", err2.Error()) + } +} From cf4be71f504808765e05b9377cfdf7fcbc39de17 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 3 Apr 2017 12:36:54 +1000 Subject: [PATCH 08/37] Added config_encryption.go --- config/config_tests/config_encryption_test.go | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 config/config_tests/config_encryption_test.go diff --git a/config/config_tests/config_encryption_test.go b/config/config_tests/config_encryption_test.go new file mode 100644 index 00000000..e51c1a87 --- /dev/null +++ b/config/config_tests/config_encryption_test.go @@ -0,0 +1,76 @@ +package test + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/gocryptotrader/config" +) + +func TestPromptForConfigEncryption(t *testing.T) { + t.Parallel() + + promptForConfigEncryption := config.GetConfig() + + if promptForConfigEncryption.PromptForConfigEncryption() { + t.Error("Test failed. PromptForConfigEncryption return incorrect bool") + } +} + +func TestPromptForConfigKey(t *testing.T) { + t.Parallel() + + byteyBite, err := config.PromptForConfigKey() + if err == nil && len(byteyBite) > 1 { + t.Errorf("Test failed. PromptForConfigKey: %s", err) + } +} + +func TestEncryptDecryptConfigFile(t *testing.T) { //Dual function Test + t.Parallel() + + testKey := []byte("12345678901234567890123456789012") + testConfigData, err := common.ReadFile("config.dat") + if err != nil { + t.Errorf("Test failed. EncryptConfigFile: %s", err) + } + encryptedFile, err2 := config.EncryptConfigFile(testConfigData, testKey) + if err2 != nil { + t.Errorf("Test failed. EncryptConfigFile: %s", err2) + } + if reflect.TypeOf(encryptedFile).String() != "[]uint8" { + t.Errorf("Test failed. EncryptConfigFile: Incorrect Type") + } + + decryptedFile, err3 := config.DecryptConfigFile(encryptedFile, testKey) + if err3 != nil { + t.Errorf("Test failed. DecryptConfigFile: %s", err3) + } + if reflect.TypeOf(decryptedFile).String() != "[]uint8" { + t.Errorf("Test failed. DecryptConfigFile: Incorrect Type") + } + unmarshalled := config.Config{} + err4 := json.Unmarshal(decryptedFile, &unmarshalled) + if err4 != nil { + t.Errorf("Test failed. DecryptConfigFile: %s", err3) + } +} + +func TestConfirmJson(t *testing.T) { + t.Parallel() + + var result interface{} + testConfirmJson, err := common.ReadFile("config.dat") + if err != nil { + t.Errorf("Test failed. TestConfirmJson: %s", err) + } + err2 := config.ConfirmConfigJSON(testConfirmJson, result) + if err2 != nil { + t.Errorf("Test failed. TestConfirmJson: %s", err2) + } + if result == nil { + t.Errorf("Test failed. TestConfirmJson: Error Unmarshalling JSON") + } +} From bd5e3192c0e974b2a50f29d15bb150e73b1ebafe Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 3 Apr 2017 12:38:46 +1000 Subject: [PATCH 09/37] Added error handling for jsondecode --- config/config_encryption.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/config/config_encryption.go b/config/config_encryption.go index 64eca75d..0d93afd4 100644 --- a/config/config_encryption.go +++ b/config/config_encryption.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "log" + "reflect" "github.com/thrasher-/gocryptotrader/common" ) @@ -40,7 +41,7 @@ func PromptForConfigKey() ([]byte, error) { var cryptoKey []byte for len(cryptoKey) != 32 { - log.Println("Enter password (32 characters):") + fmt.Println("Enter password (32 characters):") _, err := fmt.Scanln(&cryptoKey) if err != nil { @@ -51,7 +52,6 @@ func PromptForConfigKey() ([]byte, error) { fmt.Println("Please re-enter password (32 characters):") } } - nonce := make([]byte, 12) if _, err := io.ReadFull(rand.Reader, nonce); err != nil { return nil, err @@ -101,6 +101,9 @@ func DecryptConfigFile(configData, key []byte) ([]byte, error) { } func ConfirmConfigJSON(file []byte, result interface{}) error { + if !common.StringContains(reflect.TypeOf(result).String(), "*") { + return errors.New("ConfirmConfigJSON Error: Parameter interface is not a pointer.") + } return common.JSONDecode(file, &result) } From 83b0bad4e6d7bbc4fa943c3e6f30e786cf4c2ab6 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 3 Apr 2017 12:39:44 +1000 Subject: [PATCH 10/37] General formatting config_test.go --- config/config_tests/config_test.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/config/config_tests/config_test.go b/config/config_tests/config_test.go index 23829c77..c27f4dc2 100644 --- a/config/config_tests/config_test.go +++ b/config/config_tests/config_test.go @@ -77,8 +77,6 @@ func TestCheckExchangeConfigValues(t *testing.T) { t.Errorf("Test failed. checkExchangeConfigValues.LoadConfig: %s", err.Error()) } - checkExchangeConfigValues.Exchanges[0].AuthenticatedAPISupport = true - err3 := checkExchangeConfigValues.CheckExchangeConfigValues() if err3 != nil { t.Errorf("Test failed. checkExchangeConfigValues.CheckExchangeConfigValues: %s", err.Error()) @@ -119,7 +117,7 @@ func TestReadConfig(t *testing.T) { readConfig := config.GetConfig() err := readConfig.ReadConfig() if err != nil { - t.Error("Test failed. TestReadConfig" + err.Error()) + t.Error("Test failed. TestReadConfig " + err.Error()) } } @@ -129,7 +127,7 @@ func TestLoadConfig(t *testing.T) { loadConfig := config.GetConfig() err := loadConfig.LoadConfig() if err != nil { - t.Error("Test failed. TestLoadConfig" + err.Error()) + t.Error("Test failed. TestLoadConfig " + err.Error()) } } From 66cc94d31082c41624751495bdbb99877211d1e1 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 3 Apr 2017 19:21:49 +1000 Subject: [PATCH 11/37] Added Confirm and Delete ECS tests. --- config/config_tests/config_encryption_test.go | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/config/config_tests/config_encryption_test.go b/config/config_tests/config_encryption_test.go index e51c1a87..338ddf88 100644 --- a/config/config_tests/config_encryption_test.go +++ b/config/config_tests/config_encryption_test.go @@ -66,7 +66,7 @@ func TestConfirmJson(t *testing.T) { if err != nil { t.Errorf("Test failed. TestConfirmJson: %s", err) } - err2 := config.ConfirmConfigJSON(testConfirmJson, result) + err2 := config.ConfirmConfigJSON(testConfirmJson, &result) if err2 != nil { t.Errorf("Test failed. TestConfirmJson: %s", err2) } @@ -74,3 +74,23 @@ func TestConfirmJson(t *testing.T) { t.Errorf("Test failed. TestConfirmJson: Error Unmarshalling JSON") } } + +func TestConfirmECS(t *testing.T) { + t.Parallel() + + ECStest := []byte("THORS-HAMMER") + if !config.ConfirmECS(ECStest) { + t.Errorf("Test failed. TestConfirmECS: Error finding ECS.") + } +} + +func TestRemoveECS(t *testing.T) { + t.Parallel() + + ECStest := []byte("THORS-HAMMER") + isremoved := config.RemoveECS(ECStest) + + if string(isremoved) != "" { + t.Errorf("Test failed. TestConfirmECS: Error ECS not deleted.") + } +} From c57961170621d5a5edc3bfe7d8dea0dbe8634b3f Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Wed, 5 Apr 2017 13:01:19 +1000 Subject: [PATCH 12/37] added test module for currency.go --- currency/currency_tests/currency_test.go | 270 +++++++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 currency/currency_tests/currency_test.go diff --git a/currency/currency_tests/currency_test.go b/currency/currency_tests/currency_test.go new file mode 100644 index 00000000..ca647382 --- /dev/null +++ b/currency/currency_tests/currency_test.go @@ -0,0 +1,270 @@ +package tests + +import ( + "reflect" + "testing" + + "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/gocryptotrader/currency" +) + +func TestIsDefaultCurrency(t *testing.T) { + t.Parallel() + + var str1, str2, str3 string = "USD", "usd", "cats123" + + if !currency.IsDefaultCurrency(str1) { + t.Errorf("Test Failed. TestIsDefaultCurrency: \nCannot match currency, %s.", str1) + } + if !currency.IsDefaultCurrency(str2) { + t.Errorf("Test Failed. TestIsDefaultCurrency: \nCannot match currency, %s.", str2) + } + if currency.IsDefaultCurrency(str3) { + t.Errorf("Test Failed. TestIsDefaultCurrency: \nFunction return is incorrect with, %s.", str3) + } +} + +func TestIsDefaultCryptocurrency(t *testing.T) { + t.Parallel() + + var str1, str2, str3 string = "BTC", "btc", "dogs123" + + if !currency.IsDefaultCryptocurrency(str1) { + t.Errorf("Test Failed. TestIsDefaultCryptocurrency: \nCannot match currency, %s.", str1) + } + if !currency.IsDefaultCryptocurrency(str2) { + t.Errorf("Test Failed. TestIsDefaultCryptocurrency: \nCannot match currency, %s.", str2) + } + if currency.IsDefaultCryptocurrency(str3) { + t.Errorf("Test Failed. TestIsDefaultCryptocurrency: \nFunction return is incorrect with, %s.", str3) + } +} + +func TestIsFiatCurrency(t *testing.T) { + t.Parallel() + + currency.BaseCurrencies = "USD,AUD" + + var str1, str2, str3 string = "BTC", "USD", "birds123" + + if currency.IsFiatCurrency(str1) { + t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str1) + } + if !currency.IsFiatCurrency(str2) { + t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str2) + } + if currency.IsFiatCurrency(str3) { + t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str3) + } +} + +func TestIsCryptocurrency(t *testing.T) { + t.Parallel() + + currency.CryptoCurrencies = "BTC,LTC,DASH" + var str1, str2, str3 string = "USD", "BTC", "pterodactyl123" + + if currency.IsCryptocurrency(str1) { + t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str1) + } + if !currency.IsCryptocurrency(str2) { + t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str2) + } + if currency.IsCryptocurrency(str3) { + t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str3) + } +} + +func TestContainsSeparator(t *testing.T) { + t.Parallel() + + var str1, str2, str3, str4 string = "ding-dong", "ding_dong", "dong_ding-dang", "ding" + + doesIt, whatIsIt := currency.ContainsSeparator(str1) + if doesIt != true || whatIsIt != "-" { + t.Errorf("Test Failed. ContainsSeparator: \nCannot find separator, %s.", str1) + } + doesIt2, whatIsIt2 := currency.ContainsSeparator(str2) + if doesIt2 != true || whatIsIt2 != "_" { + t.Errorf("Test Failed. ContainsSeparator: \nCannot find separator, %s.", str2) + } + doesIt3, whatIsIt3 := currency.ContainsSeparator(str3) + if doesIt3 != true || len(whatIsIt3) != 3 { + t.Errorf("Test Failed. ContainsSeparator: \nCannot find or incorrect separator, %s.", str3) + } + doesIt4, whatIsIt4 := currency.ContainsSeparator(str4) + if doesIt4 != false || whatIsIt4 != "" { + t.Errorf("Test Failed. ContainsSeparator: \nReturn Issues with string, %s.", str3) + } +} + +func TestContainsBaseCurrencyIndex(t *testing.T) { + t.Parallel() + + baseCurrencies := []string{"USD", "AUD", "EUR", "CNY"} + currency1, currency2 := "USD", "DINGDONG" + + isIt, whatIsIt := currency.ContainsBaseCurrencyIndex(baseCurrencies, currency1) + if !isIt && whatIsIt != "USD" { + t.Errorf("Test Failed. ContainsBaseCurrencyIndex: \nReturned: %t & %s, with Currency as %s.", isIt, whatIsIt, currency1) + } + isIt2, whatIsIt2 := currency.ContainsBaseCurrencyIndex(baseCurrencies, currency2) + if isIt2 && whatIsIt2 != "DINGDONG" { + t.Errorf("Test Failed. ContainsBaseCurrencyIndex: \nReturned: %t & %s, with Currency as %s.", isIt2, whatIsIt2, currency2) + } +} + +func TestContainsBaseCurrency(t *testing.T) { + t.Parallel() + + baseCurrencies := []string{"USD", "AUD", "EUR", "CNY"} + currency1, currency2 := "USD", "DINGDONG" + + isIt := currency.ContainsBaseCurrency(baseCurrencies, currency1) + if !isIt { + t.Errorf("Test Failed. ContainsBaseCurrency: \nReturned: %t, with Currency as %s.", isIt, currency1) + } + isIt2 := currency.ContainsBaseCurrency(baseCurrencies, currency2) + if isIt2 { + t.Errorf("Test Failed. ContainsBaseCurrency: \nReturned: %t, with Currency as %s.", isIt2, currency2) + } +} + +func TestCheckAndAddCurrency(t *testing.T) { + t.Parallel() + + inputFiat := []string{"USD", "AUD", "EUR"} + inputCrypto := []string{"BTC", "LTC", "ETH", "DOGE", "DASH", "XRP"} + fiat := "USD" + fiatIncrease := "CNY" + crypto := "LTC" + cryptoIncrease := "XMR" + obtuse := "CATSANDDOGS" + + appendedString := currency.CheckAndAddCurrency(inputFiat, fiat) + if len(appendedString) > len(inputFiat) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", fiat) + } + appendedString = currency.CheckAndAddCurrency(inputFiat, fiatIncrease) + if len(appendedString) <= len(inputFiat) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", fiatIncrease) + } + appendedString = currency.CheckAndAddCurrency(inputFiat, crypto) + if len(appendedString) > len(inputFiat) { + t.Log(appendedString) + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", crypto) + } + appendedString = currency.CheckAndAddCurrency(inputFiat, obtuse) + if len(appendedString) > len(inputFiat) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", obtuse) + } + + appendedString = currency.CheckAndAddCurrency(inputCrypto, crypto) + if len(appendedString) > len(inputCrypto) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", crypto) + } + appendedString = currency.CheckAndAddCurrency(inputCrypto, cryptoIncrease) + if len(appendedString) <= len(inputCrypto) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", cryptoIncrease) + } + appendedString = currency.CheckAndAddCurrency(inputCrypto, fiat) + if len(appendedString) > len(inputCrypto) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", fiat) + } + appendedString = currency.CheckAndAddCurrency(inputCrypto, obtuse) + if len(appendedString) > len(inputCrypto) { + t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", obtuse) + } +} + +func TestSeedCurrencyData(t *testing.T) { + t.Parallel() + + currencyRequestDefault := "" + currencyRequestUSDAUD := "USD,AUD" + currencyRequestObtuse := "WigWham" + + err := currency.SeedCurrencyData(currencyRequestDefault) + if err != nil { + t.Errorf("Test Failed. SeedCurrencyData: Error %s with currency as %s.", err, currencyRequestDefault) + } + err2 := currency.SeedCurrencyData(currencyRequestUSDAUD) + if err2 != nil { + t.Errorf("Test Failed. SeedCurrencyData: Error %s with currency as %s.", err2, currencyRequestUSDAUD) + } + err3 := currency.SeedCurrencyData(currencyRequestObtuse) + if err3 == nil { + t.Errorf("Test Failed. SeedCurrencyData: Error %s with currency as %s.", err3, currencyRequestObtuse) + } +} + +func TestMakecurrencyPairs(t *testing.T) { + t.Parallel() + + lengthDefault := len(common.SplitStrings(currency.DEFAULT_CURRENCIES, ",")) + fiatPairsLength := len(common.SplitStrings(currency.MakecurrencyPairs(currency.DEFAULT_CURRENCIES), ",")) + + if lengthDefault*(lengthDefault-1) > fiatPairsLength { + t.Error("Test Failed. MakecurrencyPairs: Error, mismatched length") + } +} + +func TestConvertCurrency(t *testing.T) { + t.Parallel() + + fiatCurrencies := currency.DEFAULT_CURRENCIES + for _, currencyFrom := range common.SplitStrings(fiatCurrencies, ",") { + for _, currencyTo := range common.SplitStrings(fiatCurrencies, ",") { + if currencyFrom == currencyTo { + continue + } else { + floatyMcfloat, err := currency.ConvertCurrency(1000, currencyFrom, currencyTo) + if err != nil { + t.Errorf("Test Failed. ConvertCurrency: Error %s with return: %.2f Currency 1: %s Currency 2: %s", + err, floatyMcfloat, currencyFrom, currencyTo) + } + if reflect.TypeOf(floatyMcfloat).String() != "float64" { + t.Error("Test Failed. ConvertCurrency: Error, incorrect return type") + } + if floatyMcfloat <= 0 { + t.Error("Test Failed. ConvertCurrency: Error, negative return or a serious issue with current fiat") + } + } + } + } +} + +func TestFetchYahooCurrencyData(t *testing.T) { + t.Parallel() + var fetchData []string + fiatCurrencies := currency.DEFAULT_CURRENCIES + + for _, currencyOne := range common.SplitStrings(fiatCurrencies, ",") { + for _, currencyTwo := range common.SplitStrings(fiatCurrencies, ",") { + if currencyOne == currencyTwo { + continue + } else { + fetchData = append(fetchData, currencyOne+currencyTwo) + } + } + } + err := currency.FetchYahooCurrencyData(fetchData) + if err != nil { + t.Errorf("Test Failed. FetchYahooCurrencyData: Error %s", err) + } +} + +func TestQueryYahooCurrencyValues(t *testing.T) { + t.Parallel() + + err := currency.QueryYahooCurrencyValues(currency.DEFAULT_CURRENCIES) + if err != nil { + t.Errorf("Test Failed. QueryYahooCurrencyValues: Error, %s", err) + } + + err2 := currency.QueryYahooCurrencyValues(currency.DEFAULT_CRYPTOCURRENCIES) + if err2 == nil { + t.Errorf("Test Failed. QueryYahooCurrencyValues: Error, %s", err2) + } + +} From 94fc25ce255bf3f50de014b82eb30e30cfbd2b1a Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Wed, 5 Apr 2017 13:03:30 +1000 Subject: [PATCH 13/37] Added functionality and future handling for currency.go --- currency/currency.go | 51 +++++++++++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/currency/currency.go b/currency/currency.go index 2295546e..c4ee3471 100644 --- a/currency/currency.go +++ b/currency/currency.go @@ -63,21 +63,33 @@ func IsDefaultCryptocurrency(currency string) bool { } func IsFiatCurrency(currency string) bool { + if BaseCurrencies == "" { + log.Println("IsFiatCurrency: BaseCurrencies string variable not populated") + } return common.StringContains(BaseCurrencies, common.StringToUpper(currency)) } func IsCryptocurrency(currency string) bool { + if CryptoCurrencies == "" { + log.Println("IsCryptocurrency: CryptoCurrencies string variable not populated") + } return common.StringContains(CryptoCurrencies, common.StringToUpper(currency)) } func ContainsSeparator(input string) (bool, string) { separators := []string{"-", "_"} + var separatorsContainer []string + for _, x := range separators { if common.StringContains(input, x) { - return true, x + separatorsContainer = append(separatorsContainer, x) } } - return false, "" + if len(separatorsContainer) == 0 { + return false, "" + } else { + return true, strings.Join(separatorsContainer, ",") + } } func ContainsBaseCurrencyIndex(baseCurrencies []string, currency string) (bool, string) { @@ -100,13 +112,28 @@ func ContainsBaseCurrency(baseCurrencies []string, currency string) bool { func CheckAndAddCurrency(input []string, check string) []string { for _, x := range input { - if check == x { + if IsDefaultCurrency(x) { + if IsDefaultCurrency(check) { + if check == x { + return input + } + continue + } else { + return input + } + } else if IsDefaultCryptocurrency(x) { + if IsDefaultCryptocurrency(check) { + if check == x { + return input + } + continue + } else { + return input + } + } else { return input } } - if IsCryptocurrency(check) && IsFiatCurrency(check) { - return input - } input = append(input, check) return input @@ -118,7 +145,6 @@ func SeedCurrencyData(fiatCurrencies string) error { } err := QueryYahooCurrencyValues(fiatCurrencies) - if err != nil { return ErrQueryingYahoo } @@ -142,16 +168,15 @@ func MakecurrencyPairs(supportedCurrencies string) string { } func ConvertCurrency(amount float64, from, to string) (float64, error) { - if len(CurrencyStore) == 0 { - err := SeedCurrencyData(common.StringToUpper(from) + "," + common.StringToUpper(to)) + currency := common.StringToUpper(from + to) + + if CurrencyStore[currency].Name != currency { + err := SeedCurrencyData(currency[:len(from)] + "," + currency[len(to):]) if err != nil { return 0, err } } - currency := common.StringToUpper(from + to) - if common.StringContains(currency, "RUB") { - currency = strings.Replace(currency, "RUB", "RUR", -1) - } + for x, y := range CurrencyStore { if x == currency { return amount * y.Rate, nil From c94ac92b6d79a3dbfc2a7af443bcc7959ce86350 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Thu, 6 Apr 2017 17:32:05 +1000 Subject: [PATCH 14/37] Added more functionality to package --- events/events.go | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/events/events.go b/events/events.go index d2c1ad73..d0dc885f 100644 --- a/events/events.go +++ b/events/events.go @@ -8,6 +8,7 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" + "github.com/thrasher-/gocryptotrader/currency" "github.com/thrasher-/gocryptotrader/exchanges/ticker" "github.com/thrasher-/gocryptotrader/smsglobal" ) @@ -24,11 +25,11 @@ const ( ) var ( - ErrInvalidItem = errors.New("Invalid item.") - ErrInvalidCondition = errors.New("Invalid conditional option.") - ErrInvalidAction = errors.New("Invalid action.") - ErrExchangeDisabled = errors.New("Desired exchange is disabled.") - ErrFiatCurrencyInvalid = errors.New("Invalid fiat currency.") + ErrInvalidItem = errors.New("Invalid item.") + ErrInvalidCondition = errors.New("Invalid conditional option.") + ErrInvalidAction = errors.New("Invalid action.") + ErrExchangeDisabled = errors.New("Desired exchange is disabled.") + ErrCurrencyInvalid = errors.New("Invalid currency.") ) type Event struct { @@ -46,11 +47,14 @@ var Events []*Event func AddEvent(Exchange, Item, Condition, FirstCurrency, SecondCurrency, Action string) (int, error) { err := IsValidEvent(Exchange, Item, Condition, Action) - if err != nil { return 0, err } + if !IsValidCurrency(FirstCurrency, SecondCurrency) { + return 0, ErrCurrencyInvalid + } + Event := &Event{} if len(Events) == 0 { @@ -114,7 +118,7 @@ func (e *Event) EventToString() string { return fmt.Sprintf("If the %s%s %s on %s is %s then %s.", e.FirstCurrency, e.SecondCurrency, e.Item, e.Exchange, condition[0]+" "+condition[1], e.Action) } -func (e *Event) CheckCondition() bool { +func (e *Event) CheckCondition() bool { //Add error handling lastPrice := 0.00 condition := common.SplitStrings(e.Condition, ",") targetPrice, _ := strconv.ParseFloat(condition[1], 64) @@ -166,6 +170,10 @@ func (e *Event) CheckCondition() bool { } func IsValidEvent(Exchange, Item, Condition, Action string) error { + Exchange = common.StringToUpper(Exchange) + Item = common.StringToUpper(Item) + Action = common.StringToUpper(Action) + if !IsValidExchange(Exchange) { return ErrExchangeDisabled } @@ -219,8 +227,27 @@ func CheckEvents() { } } +func IsValidCurrency(currencies ...string) bool { + for _, whatIsIt := range currencies { + whatIsIt = common.StringToUpper(whatIsIt) + if currency.IsDefaultCryptocurrency(whatIsIt) { + return true + } + if currency.IsDefaultCurrency(whatIsIt) { + return true + } + } + return false +} + func IsValidExchange(Exchange string) bool { + Exchange = common.StringToUpper(Exchange) + cfg := config.GetConfig() + if len(cfg.Exchanges) == 0 { + cfg.LoadConfig() + } + for _, x := range cfg.Exchanges { if x.Name == Exchange && x.Enabled { return true @@ -238,6 +265,7 @@ func IsValidCondition(Condition string) bool { } func IsValidAction(Action string) bool { + Action = common.StringToUpper(Action) switch Action { case ACTION_SMS_NOTIFY, ACTION_CONSOLE_PRINT: return true @@ -246,6 +274,7 @@ func IsValidAction(Action string) bool { } func IsValidItem(Item string) bool { + Item = common.StringToUpper(Item) switch Item { case ITEM_PRICE: return true From 8096603c8c419fdd29a4b6fe296c715a23b9591c Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Thu, 6 Apr 2017 17:33:50 +1000 Subject: [PATCH 15/37] Added tests for events.go --- events/event_tests/event_test.go | 219 +++++++++++++++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 events/event_tests/event_test.go diff --git a/events/event_tests/event_test.go b/events/event_tests/event_test.go new file mode 100644 index 00000000..041baebc --- /dev/null +++ b/events/event_tests/event_test.go @@ -0,0 +1,219 @@ +package tests + +import ( + "testing" + + "github.com/thrasher-/gocryptotrader/events" +) + +func TestAddEvent(t *testing.T) { + eventID, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil && eventID != 0 { + t.Errorf("Test Failed. AddEvent: Error, %s", err) + } + eventID, err = events.AddEvent("ANXX", "price", ">,==", "BTC", "LTC", "console_print") + if err == nil && eventID == 0 { + t.Error("Test Failed. AddEvent: Error, error not captured in Exchange") + } + eventID, err = events.AddEvent("ANX", "prices", ">,==", "BTC", "LTC", "console_print") + if err == nil && eventID == 0 { + t.Error("Test Failed. AddEvent: Error, error not captured in Item") + } + eventID, err = events.AddEvent("ANX", "price", "3===D", "BTC", "LTC", "console_print") + if err == nil && eventID == 0 { + t.Error("Test Failed. AddEvent: Error, error not captured in Condition") + } + eventID, err = events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_prints") + if err == nil && eventID == 0 { + t.Error("Test Failed. AddEvent: Error, error not captured in Action") + } + eventID, err = events.AddEvent("ANX", "price", ">,==", "BATMAN", "ROBIN", "console_print") + if err == nil && eventID == 0 { + t.Error("Test Failed. AddEvent: Error, error not captured in Action") + } + if !events.RemoveEvent(eventID) { + t.Error("Test Failed. RemoveEvent: Error, error removing event") + } +} + +func TestRemoveEvent(t *testing.T) { + eventID, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil && eventID != 0 { + t.Errorf("Test Failed. RemoveEvent: Error, %s", err) + } + if !events.RemoveEvent(eventID) { + t.Error("Test Failed. RemoveEvent: Error, error removing event") + } +} + +func TestGetEventCounter(t *testing.T) { + one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil { + t.Errorf("Test Failed. GetEventCounter: Error, %s", err) + } + two, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil { + t.Errorf("Test Failed. GetEventCounter: Error, %s", err) + } + three, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil { + t.Errorf("Test Failed. GetEventCounter: Error, %s", err) + } + + total, _ := events.GetEventCounter() + if total <= 0 { + t.Errorf("Test Failed. GetEventCounter: Total = %d", total) + } + + if !events.RemoveEvent(one) { + t.Error("Test Failed. GetEventCounter: Error, error removing event") + } + if !events.RemoveEvent(two) { + t.Error("Test Failed. GetEventCounter: Error, error removing event") + } + if !events.RemoveEvent(three) { + t.Error("Test Failed. GetEventCounter: Error, error removing event") + } + + total2, _ := events.GetEventCounter() + t.Log(total2) + if total2 != 0 { + t.Errorf("Test Failed. GetEventCounter: Total = %d", total2) + } +} + +func TestExecuteAction(t *testing.T) { + t.Parallel() + + one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil { + t.Errorf("Test Failed. ExecuteAction: Error, %s", err) + } + isExecuted := events.Events[one].ExecuteAction() + if !isExecuted { + t.Error("Test Failed. ExecuteAction: Error, error removing event") + } + + if !events.RemoveEvent(one) { + t.Error("Test Failed. ExecuteAction: Error, error removing event") + } +} + +func TestEventToString(t *testing.T) { + t.Parallel() + + one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil { + t.Errorf("Test Failed. EventToString: Error, %s", err) + } + + eventString := events.Events[one].EventToString() + if eventString != "If the BTCLTC price on ANX is > == then console_print." { + t.Error("Test Failed. EventToString: Error, incorrect return string") + } + + if !events.RemoveEvent(one) { + t.Error("Test Failed. EventToString: Error, error removing event") + } + +} + +func TestCheckCondition(t *testing.T) { //error handling needs to be implemented + t.Parallel() + + one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + if err != nil { + t.Errorf("Test Failed. EventToString: Error, %s", err) + } + + conditionBool := events.Events[one].CheckCondition() + if conditionBool { //check once error handling is implemented + t.Error("Test Failed. EventToString: Error, wrong conditional.") + } + + if !events.RemoveEvent(one) { + t.Error("Test Failed. EventToString: Error, error removing event") + } + +} + +func TestIsValidEvent(t *testing.T) { + err := events.IsValidEvent("ANX", "price", ">,==", "console_print") + if err != nil { + t.Errorf("Test Failed. IsValidExchange: Error %s", err) + } +} + +func TestCheckEvents(t *testing.T) { //Add error handling + //events.CheckEvents() //check once error handling is implemented +} + +func TestIsValidExchange(t *testing.T) { + boolean := events.IsValidExchange("ANX") + if !boolean { + t.Error("Test Failed. IsValidExchange: Error, incorrect Exchange") + } + boolean = events.IsValidExchange("OBTUSE") + if boolean { + t.Error("Test Failed. IsValidExchange: Error, incorrect return") + } +} + +func TestIsValidCondition(t *testing.T) { + t.Parallel() + + boolean := events.IsValidCondition(">") + if !boolean { + t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") + } + boolean = events.IsValidCondition(">=") + if !boolean { + t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") + } + boolean = events.IsValidCondition("<") + if !boolean { + t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") + } + boolean = events.IsValidCondition("<=") + if !boolean { + t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") + } + boolean = events.IsValidCondition("==") + if !boolean { + t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") + } + boolean = events.IsValidCondition("**********") + if boolean { + t.Error("Test Failed. IsValidCondition: Error, incorrect return") + } +} + +func TestIsValidAction(t *testing.T) { + t.Parallel() + + boolean := events.IsValidAction("sms") + if !boolean { + t.Error("Test Failed. IsValidAction: Error, incorrect Action") + } + boolean = events.IsValidAction("console_print") + if !boolean { + t.Error("Test Failed. IsValidAction: Error, incorrect Action") + } + boolean = events.IsValidAction("randomstring") + if boolean { + t.Error("Test Failed. IsValidAction: Error, incorrect return") + } +} + +func TestIsValidItem(t *testing.T) { + t.Parallel() + + boolean := events.IsValidItem("price") + if !boolean { + t.Error("Test Failed. IsValidItem: Error, incorrect Item") + } + boolean = events.IsValidItem("obtuse") + if boolean { + t.Error("Test Failed. IsValidItem: Error, incorrect return") + } +} From 2565c6497f53671de7bb8d914aeb5d3bb48f3b89 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Fri, 7 Apr 2017 15:21:25 +1000 Subject: [PATCH 16/37] Added test module for Smsglobal.go --- smsglobal/smsglobal_tests/config_example.dat | 287 +++++++++++++++++++ smsglobal/smsglobal_tests/smsglobal_test.go | 56 ++++ 2 files changed, 343 insertions(+) create mode 100644 smsglobal/smsglobal_tests/config_example.dat create mode 100644 smsglobal/smsglobal_tests/smsglobal_test.go diff --git a/smsglobal/smsglobal_tests/config_example.dat b/smsglobal/smsglobal_tests/config_example.dat new file mode 100644 index 00000000..973ffa04 --- /dev/null +++ b/smsglobal/smsglobal_tests/config_example.dat @@ -0,0 +1,287 @@ +{ + "Name": "Skynet", + "EncryptConfig": 0, + "Cryptocurrencies": "BTC,LTC,ETH,XRP,NMC,NVC,PPC,XBT,DOGE,DASH", + "PortfolioAddresses": { + "Addresses": [ + { + "Address": "1JCe8z4jJVNXSjohjM4i9Hh813dLCNx2Sy", + "CoinType": "BTC", + "Balance": 124178.0002442 + }, + { + "Address": "3Nxwenay9Z8Lc9JBiywExpnEFiLp6Afp8v", + "CoinType": "BTC", + "Balance": 103439.83659727 + }, + { + "Address": "LgY8ahfHRhvjVQC1zJnBhFMG5pCTMuKRqh", + "CoinType": "LTC", + "Balance": 3.00000005e+06 + }, + { + "Address": "0xb794f5ea0ba39494ce839613fffba74279579268", + "CoinType": "ETH", + "Balance": 5.774999820458524e+06 + } + ] + }, + "SMSGlobal": { + "Enabled": false, + "Username": "Username", + "Password": "Password", + "Contacts": [ + { + "Name": "Bob", + "Number": "12345", + "Enabled": false + } + ] + }, + "Webserver": { + "Enabled": false, + "AdminUsername": "admin", + "AdminPassword": "Password", + "ListenAddress": ":9050" + }, + "Exchanges": [ + { + "Name": "ANX", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", + "EnabledPairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", + "BaseCurrencies": "USD,HKD,EUR,CAD,AUD,SGD,JPY,GBP,NZD" + }, + { + "Name": "Bitfinex", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC,ETCBTC,ETCUSD,BFXUSD,BFXBTC,RRTUSD,RRTBTC,ZECUSD,ZECBTC,XMRUSD,XMRBTC,DSHUSD,DSHBTC", + "EnabledPairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC", + "BaseCurrencies": "USD" + }, + { + "Name": "Bitstamp", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "ClientID", + "AvailablePairs": "BTCUSD,BTCEUR,EURUSD,XRPUSD,XRPEUR", + "EnabledPairs": "BTCUSD,BTCEUR,EURUSD,XRPUSD,XRPEUR", + "BaseCurrencies": "USD,EUR" + }, + { + "Name": "BTCC", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCCNY,LTCCNY,LTCBTC", + "EnabledPairs": "BTCCNY,LTCCNY,LTCBTC", + "BaseCurrencies": "CNY" + }, + { + "Name": "BTCE", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", + "EnabledPairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", + "BaseCurrencies": "USD,RUR,EUR" + }, + { + "Name": "BTC Markets", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "LTC,BTC", + "EnabledPairs": "LTC,BTC", + "BaseCurrencies": "AUD" + }, + { + "Name": "GDAX", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "ClientID", + "AvailablePairs": "BTCGBP,BTCEUR,ETHUSD,ETHBTC,LTCUSD,LTCBTC,BTCUSD", + "EnabledPairs": "BTCUSD,BTCGBP,BTCEUR", + "BaseCurrencies": "USD,GBP,EUR" + }, + { + "Name": "Gemini", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,ETHBTC,ETHUSD", + "EnabledPairs": "BTCUSD", + "BaseCurrencies": "USD" + }, + { + "Name": "Huobi", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCCNY,LTCCNY", + "EnabledPairs": "BTCCNY,LTCCNY", + "BaseCurrencies": "CNY" + }, + { + "Name": "ITBIT", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "ClientID", + "AvailablePairs": "XBTUSD,XBTSGD,XBTEUR", + "EnabledPairs": "XBTUSD,XBTSGD,XBTEUR", + "BaseCurrencies": "USD,SGD,EUR" + }, + { + "Name": "Kraken", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "ETCUSD,ICNETH,REPXBT,ZECXBT,ETHXBT,ETHXBT.d,ETHGBP,LTCXBT,XBTGBP.d,XDGXBT,XMRUSD,ZECUSD,ETCETH,ETHJPY,XBTCAD.d,XBTJPY.d,XBTUSD.d,XLMXBT,XLMEUR,XLMUSD,XMREUR,ETCXBT,ETHCAD.d,ETHEUR.d,ETHJPY.d,XBTEUR.d,ETHEUR,ETHGBP.d,ICNXBT,LTCEUR,REPEUR,XBTGBP,XBTJPY,ETHUSD,ETHUSD.d,LTCUSD,REPETH,XBTUSD,XMRXBT,ETCEUR,ETHCAD,REPUSD,XBTCAD,XBTEUR,XRPXBT,ZECEUR", + "EnabledPairs": "ETCUSD,XBTUSD,ETHUSD", + "BaseCurrencies": "EUR,USD,CAD,GBP,JPY" + }, + { + "Name": "LakeBTC", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,BTCEUR,USDHKD,AUDUSD,BTCGBP,BTCNZD,USDJPY,BTCSGD,BTCNGN,EURUSD,USDSGD,NZDUSD,USDNGN,USDCHF,BTCJPY,BTCAUD,BTCCAD,BTCCHF,GBPUSD,USDCAD", + "EnabledPairs": "BTCUSD,BTCAUD", + "BaseCurrencies": "USD,EUR,HKD,AUD,GBP,NZD,JPY,SGD,NGN,CHF,CAD" + }, + { + "Name": "Liqui", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "TIME_BTC,ETH_BTC,GNT_BTC,WAVES_BTC,ICN_BTC,1ST_BTC,WINGS_BTC,MLN_BTC,ROUND_BTC,VSL_BTC,LTC_BTC,DCT_BTC,INCNT_BTC,PLU_BTC,DASH_BTC", + "EnabledPairs": "ETH_BTC,LTC_BTC,DASH_BTC", + "BaseCurrencies": "USD" + }, + { + "Name": "LocalBitcoins", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", + "EnabledPairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", + "BaseCurrencies": "ARS,AUD,BRL,CAD,CHF,CZK,DKK,EUR,GBP,HKD,ILS,INR,MXN,NOK,NZD,PLN,RUB,SEK,SGD,THB,USD,ZAR" + }, + { + "Name": "OKCOIN China", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCCNY,LTCCNY", + "EnabledPairs": "BTCCNY,LTCCNY", + "BaseCurrencies": "CNY" + }, + { + "Name": "OKCOIN International", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTCUSD,LTCUSD", + "EnabledPairs": "BTCUSD,LTCUSD", + "BaseCurrencies": "USD" + }, + { + "Name": "Poloniex", + "Enabled": true, + "Verbose": false, + "Websocket": false, + "RESTPollingDelay": 10, + "AuthenticatedAPISupport": false, + "APIKey": "Key", + "APISecret": "Secret", + "ClientID": "", + "AvailablePairs": "BTC_XUSD,BTC_FCT,BTC_MMNXT,BTC_NMC,BTC_BITUSD,BTC_RDD,BTC_XMR,BTC_XST,BTC_DSH,BTC_MAID,BTC_DGB,BTC_NEOS,BTC_BLK,BTC_NAUT,BTC_NBT,BTC_XCP,BTC_STR,BTC_BTCD,BTC_GRC,BTC_HUC,BTC_BBR,BTC_XDN,BTC_INDEX,BTC_IOC,BTC_SWARM,BTC_EMC2,BTC_MCN,BTC_NOXT,BTC_MINT,BTC_PTS,BTC_SC,BTC_GEO,BTC_XRP,BTC_FLO,BTC_BITS,BTC_HYP,BTC_XCR,BTC_LTBC,BTC_SYS,BTC_GMC,BTC_ETH,BTC_SYNC,BTC_GAP,BTC_BCN,BTC_C2,BTC_PINK,BTC_FIBRE,BTC_POT,BTC_QTL,BTC_SDC,BTC_XC,BTC_DASH,BTC_SILK,BTC_CLAM,BTC_NAV,BTC_PIGGY,BTC_BCY,BTC_MIL,BTC_XCN,BTC_YACC,BTC_BTS,BTC_QBK,BTC_SJCX,BTC_LQD,BTC_BURST,BTC_RIC,BTC_VRC,BTC_LTC,BTC_XPB,BTC_GRS,BTC_XCH,BTC_ARCH,BTC_QORA,BTC_HZ,BTC_NSR,BTC_XPM,BTC_BITCNY,BTC_EXE,BTC_XMG,BTC_BTC,BTC_BTM,BTC_NOBL,BTC_NXT,BTC_DOGE,BTC_CURE,BTC_MNTA,BTC_ADN,BTC_EXP,BTC_VTC,BTC_FLDC,BTC_MRS,BTC_MYR,BTC_OMNI,BTC_VNL,BTC_USDT,BTC_NOTE,BTC_WDC,BTC_BELA,BTC_VIA,BTC_CGA,BTC_DIEM,BTC_IFC,BTC_XDP,BTC_BLOCK,BTC_MMC,BTC_1CR,BTC_UNITY,BTC_XBC,BTC_GEMZ,BTC_FLT,BTC_PPC,BTC_XEM,BTC_RBY,BTC_CNMT,BTC_ABY,XMR_XDN,XMR_IFC,XMR_DIEM,XMR_BBR,XMR_DSH,XMR_BCN,XMR_LTC,XMR_MAID,XMR_DASH,XMR_BTCD,XMR_HYP,XMR_BLK,XMR_QORA,XMR_MNTA,XMR_NXT,USDT_BTC,USDT_ETH,USDT_XRP,USDT_DASH,USDT_LTC,USDT_NXT,USDT_XMR,USDT_STR", + "EnabledPairs": "BTC_LTC,BTC_ETH,BTC_DOGE,BTC_DASH,BTC_XRP", + "BaseCurrencies": "USD" + } + ] +} \ No newline at end of file diff --git a/smsglobal/smsglobal_tests/smsglobal_test.go b/smsglobal/smsglobal_tests/smsglobal_test.go new file mode 100644 index 00000000..413a7544 --- /dev/null +++ b/smsglobal/smsglobal_tests/smsglobal_test.go @@ -0,0 +1,56 @@ +package test + +import ( + "testing" + + "github.com/thrasher-/gocryptotrader/config" + "github.com/thrasher-/gocryptotrader/smsglobal" +) + +func TestGetEnabledSMSContacts(t *testing.T) { + cfg := config.GetConfig() + err := cfg.LoadConfig() + if err != nil { + t.Errorf("Test Failed. GetEnabledSMSContacts: \nFunction return is incorrect with, %s.", err) + } + + numberOfContacts := smsglobal.GetEnabledSMSContacts(cfg.SMS) + if numberOfContacts != 1 { + t.Errorf("Test Failed. GetEnabledSMSContacts: \nFunction return is incorrect with, %d.", numberOfContacts) + } +} + +func TestSMSSendToAll(t *testing.T) { + cfg := config.GetConfig() + err := cfg.LoadConfig() + if err != nil { + t.Errorf("Test Failed. SMSSendToAll: \nFunction return is incorrect with, %s.", err) + } + + smsglobal.SMSSendToAll("Test", *cfg) //+60sec reply issue without account details +} + +func TestSMSGetNumberByName(t *testing.T) { + cfg := config.GetConfig() + err := cfg.LoadConfig() + if err != nil { + t.Errorf("Test Failed. SMSGetNumberByName: \nFunction return is incorrect with, %s.", err) + } + number := smsglobal.SMSGetNumberByName("POLYESTERGIRL", cfg.SMS) + if number == "" { + t.Log("Isssues bra!") + } +} + +func TestSMSNotify(t *testing.T) { + cfg := config.GetConfig() + err := cfg.LoadConfig() + if err != nil { + t.Errorf("Test Failed. SMSNotify: \nFunction return is incorrect with, %s.", err) + } + + err2 := smsglobal.SMSNotify("POLYESTERGIRL", "Test", *cfg) + if err2 == nil { + t.Error("Test Failed. SMSNotify: \nError: ", err2) + } +} From a4dc2cdaae5f5a35756e8f2d8fe7587a2833758e Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Fri, 7 Apr 2017 17:52:31 +1000 Subject: [PATCH 17/37] Updated Test --- smsglobal/smsglobal_tests/smsglobal_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/smsglobal/smsglobal_tests/smsglobal_test.go b/smsglobal/smsglobal_tests/smsglobal_test.go index 413a7544..abd14cd1 100644 --- a/smsglobal/smsglobal_tests/smsglobal_test.go +++ b/smsglobal/smsglobal_tests/smsglobal_test.go @@ -15,7 +15,7 @@ func TestGetEnabledSMSContacts(t *testing.T) { } numberOfContacts := smsglobal.GetEnabledSMSContacts(cfg.SMS) - if numberOfContacts != 1 { + if numberOfContacts != len(cfg.SMS.Contacts) { t.Errorf("Test Failed. GetEnabledSMSContacts: \nFunction return is incorrect with, %d.", numberOfContacts) } } @@ -38,7 +38,7 @@ func TestSMSGetNumberByName(t *testing.T) { } number := smsglobal.SMSGetNumberByName("POLYESTERGIRL", cfg.SMS) if number == "" { - t.Log("Isssues bra!") + t.Error("Test Failed. SMSNotify: \nError: No number, name not found.") } } @@ -49,8 +49,8 @@ func TestSMSNotify(t *testing.T) { t.Errorf("Test Failed. SMSNotify: \nFunction return is incorrect with, %s.", err) } - err2 := smsglobal.SMSNotify("POLYESTERGIRL", "Test", *cfg) - if err2 == nil { + err2 := smsglobal.SMSNotify(cfg.SMS.Contacts[0].Number, "Test", *cfg) + if err2 != nil { t.Error("Test Failed. SMSNotify: \nError: ", err2) } } From 8a96f2085870f3b687e1fef0b1fd24364b4edc1a Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Sat, 8 Apr 2017 15:40:47 +1000 Subject: [PATCH 18/37] Restructured test files and added alphapoint test --- config/config.go | 37 +- config/config_encryption.go | 2 +- .../config_encryption_test.go | 29 +- config/{config_tests => }/config_test.go | 50 +-- config/config_tests/config_example.dat | 287 ------------ .../{currency_tests => }/currency_test.go | 86 ++-- events/{event_tests => }/event_test.go | 89 ++-- events/events.go | 17 +- exchanges/alphapoint/alphapoint.go | 5 +- exchanges/alphapoint/alphapoint_test.go | 413 ++++++++++++++++++ smsglobal/smsglobal.go | 2 +- .../{smsglobal_tests => }/smsglobal_test.go | 19 +- .../configtest.dat | 30 +- 13 files changed, 597 insertions(+), 469 deletions(-) rename config/{config_tests => }/config_encryption_test.go (72%) rename config/{config_tests => }/config_test.go (72%) delete mode 100644 config/config_tests/config_example.dat rename currency/{currency_tests => }/currency_test.go (73%) rename events/{event_tests => }/event_test.go (62%) create mode 100644 exchanges/alphapoint/alphapoint_test.go rename smsglobal/{smsglobal_tests => }/smsglobal_test.go (68%) rename smsglobal/smsglobal_tests/config_example.dat => testdata/configtest.dat (95%) diff --git a/config/config.go b/config/config.go index 0e873aa4..2e69eb6a 100644 --- a/config/config.go +++ b/config/config.go @@ -18,6 +18,7 @@ import ( const ( CONFIG_FILE = "config.dat" OLD_CONFIG_FILE = "config.json" + CONFIG_TEST = "../testdata/configtest.dat" CONFIG_FILE_ENCRYPTION_PROMPT = 0 CONFIG_FILE_ENCRYPTION_ENABLED = 1 @@ -265,7 +266,7 @@ func (c *Config) RetrieveConfigCurrencyPairs() error { return nil } -func (c *Config) ReadConfig() error { +func CheckConfig() error { _, err := common.ReadFile(OLD_CONFIG_FILE) if err == nil { err = os.Rename(OLD_CONFIG_FILE, CONFIG_FILE) @@ -274,8 +275,23 @@ func (c *Config) ReadConfig() error { } log.Printf(RenamingConfigFile+"\n", OLD_CONFIG_FILE, CONFIG_FILE) } + return nil +} - file, err := common.ReadFile(CONFIG_FILE) +func (c *Config) ReadConfig(configPath string) error { + defaultPath := "" + if configPath == "" { + defaultPath = CONFIG_FILE + } else { + defaultPath = configPath + } + + err := CheckConfig() + if err != nil { + return err + } + + file, err := common.ReadFile(defaultPath) if err != nil { return err } @@ -293,7 +309,7 @@ func (c *Config) ReadConfig() error { if c.EncryptConfig == CONFIG_FILE_ENCRYPTION_PROMPT { if c.PromptForConfigEncryption() { c.EncryptConfig = CONFIG_FILE_ENCRYPTION_ENABLED - return c.SaveConfig() + return c.SaveConfig("") } } } else { @@ -315,7 +331,14 @@ func (c *Config) ReadConfig() error { return nil } -func (c *Config) SaveConfig() error { +func (c *Config) SaveConfig(configPath string) error { + defaultPath := "" + if configPath == "" { + defaultPath = CONFIG_FILE + } else { + defaultPath = configPath + } + payload, err := json.MarshalIndent(c, "", " ") if c.EncryptConfig == CONFIG_FILE_ENCRYPTION_ENABLED { @@ -330,15 +353,15 @@ func (c *Config) SaveConfig() error { } } - err = common.WriteFile(CONFIG_FILE, payload) + err = common.WriteFile(defaultPath, payload) if err != nil { return err } return nil } -func (c *Config) LoadConfig() error { - err := c.ReadConfig() +func (c *Config) LoadConfig(configPath string) error { + err := c.ReadConfig(configPath) if err != nil { return fmt.Errorf(ErrFailureOpeningConfig, CONFIG_FILE, err) } diff --git a/config/config_encryption.go b/config/config_encryption.go index 0d93afd4..65d1cab6 100644 --- a/config/config_encryption.go +++ b/config/config_encryption.go @@ -31,7 +31,7 @@ func (c *Config) PromptForConfigEncryption() bool { if !common.YesOrNo(input) { c.EncryptConfig = CONFIG_FILE_ENCRYPTION_DISABLED - c.SaveConfig() + c.SaveConfig("") return false } return true diff --git a/config/config_tests/config_encryption_test.go b/config/config_encryption_test.go similarity index 72% rename from config/config_tests/config_encryption_test.go rename to config/config_encryption_test.go index 338ddf88..657ae28d 100644 --- a/config/config_tests/config_encryption_test.go +++ b/config/config_encryption_test.go @@ -1,4 +1,4 @@ -package test +package config import ( "encoding/json" @@ -6,15 +6,12 @@ import ( "testing" "github.com/thrasher-/gocryptotrader/common" - "github.com/thrasher-/gocryptotrader/config" ) func TestPromptForConfigEncryption(t *testing.T) { t.Parallel() - promptForConfigEncryption := config.GetConfig() - - if promptForConfigEncryption.PromptForConfigEncryption() { + if Cfg.PromptForConfigEncryption() { t.Error("Test failed. PromptForConfigEncryption return incorrect bool") } } @@ -22,21 +19,19 @@ func TestPromptForConfigEncryption(t *testing.T) { func TestPromptForConfigKey(t *testing.T) { t.Parallel() - byteyBite, err := config.PromptForConfigKey() + byteyBite, err := PromptForConfigKey() if err == nil && len(byteyBite) > 1 { t.Errorf("Test failed. PromptForConfigKey: %s", err) } } func TestEncryptDecryptConfigFile(t *testing.T) { //Dual function Test - t.Parallel() - testKey := []byte("12345678901234567890123456789012") - testConfigData, err := common.ReadFile("config.dat") + testConfigData, err := common.ReadFile("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. EncryptConfigFile: %s", err) } - encryptedFile, err2 := config.EncryptConfigFile(testConfigData, testKey) + encryptedFile, err2 := EncryptConfigFile(testConfigData, testKey) if err2 != nil { t.Errorf("Test failed. EncryptConfigFile: %s", err2) } @@ -44,14 +39,14 @@ func TestEncryptDecryptConfigFile(t *testing.T) { //Dual function Test t.Errorf("Test failed. EncryptConfigFile: Incorrect Type") } - decryptedFile, err3 := config.DecryptConfigFile(encryptedFile, testKey) + decryptedFile, err3 := DecryptConfigFile(encryptedFile, testKey) if err3 != nil { t.Errorf("Test failed. DecryptConfigFile: %s", err3) } if reflect.TypeOf(decryptedFile).String() != "[]uint8" { t.Errorf("Test failed. DecryptConfigFile: Incorrect Type") } - unmarshalled := config.Config{} + unmarshalled := Config{} err4 := json.Unmarshal(decryptedFile, &unmarshalled) if err4 != nil { t.Errorf("Test failed. DecryptConfigFile: %s", err3) @@ -59,14 +54,12 @@ func TestEncryptDecryptConfigFile(t *testing.T) { //Dual function Test } func TestConfirmJson(t *testing.T) { - t.Parallel() - var result interface{} - testConfirmJson, err := common.ReadFile("config.dat") + testConfirmJson, err := common.ReadFile("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. TestConfirmJson: %s", err) } - err2 := config.ConfirmConfigJSON(testConfirmJson, &result) + err2 := ConfirmConfigJSON(testConfirmJson, &result) if err2 != nil { t.Errorf("Test failed. TestConfirmJson: %s", err2) } @@ -79,7 +72,7 @@ func TestConfirmECS(t *testing.T) { t.Parallel() ECStest := []byte("THORS-HAMMER") - if !config.ConfirmECS(ECStest) { + if !ConfirmECS(ECStest) { t.Errorf("Test failed. TestConfirmECS: Error finding ECS.") } } @@ -88,7 +81,7 @@ func TestRemoveECS(t *testing.T) { t.Parallel() ECStest := []byte("THORS-HAMMER") - isremoved := config.RemoveECS(ECStest) + isremoved := RemoveECS(ECStest) if string(isremoved) != "" { t.Errorf("Test failed. TestConfirmECS: Error ECS not deleted.") diff --git a/config/config_tests/config_test.go b/config/config_test.go similarity index 72% rename from config/config_tests/config_test.go rename to config/config_test.go index c27f4dc2..305cf3c1 100644 --- a/config/config_tests/config_test.go +++ b/config/config_test.go @@ -1,17 +1,15 @@ -package test +package config import ( "testing" - - "github.com/thrasher-/gocryptotrader/config" ) func TestGetConfigEnabledExchanges(t *testing.T) { t.Parallel() defaultEnabledExchanges := 17 - GetConfigEnabledExchanges := config.GetConfig() - err := GetConfigEnabledExchanges.LoadConfig() + GetConfigEnabledExchanges := GetConfig() + err := GetConfigEnabledExchanges.LoadConfig("../testdata/configtest.dat") if err != nil { t.Error("Test failed. GetConfigEnabledExchanges load config error: " + err.Error()) } @@ -24,13 +22,13 @@ func TestGetConfigEnabledExchanges(t *testing.T) { func TestGetExchangeConfig(t *testing.T) { t.Parallel() - GetExchangeConfig := config.GetConfig() - err := GetExchangeConfig.LoadConfig() + GetExchangeConfig := GetConfig() + err := GetExchangeConfig.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. GetExchangeConfig.LoadConfig Error: %s", err.Error()) } r, err := GetExchangeConfig.GetExchangeConfig("ANX") - if err != nil && (config.ExchangeConfig{}) == r { + if err != nil && (ExchangeConfig{}) == r { t.Errorf("Test failed. GetExchangeConfig.GetExchangeConfig Error: %s", err.Error()) } } @@ -38,8 +36,8 @@ func TestGetExchangeConfig(t *testing.T) { func TestUpdateExchangeConfig(t *testing.T) { t.Parallel() - UpdateExchangeConfig := config.GetConfig() - err := UpdateExchangeConfig.LoadConfig() + UpdateExchangeConfig := GetConfig() + err := UpdateExchangeConfig.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. UpdateExchangeConfig.LoadConfig Error: %s", err.Error()) } @@ -57,8 +55,8 @@ func TestUpdateExchangeConfig(t *testing.T) { func TestCheckSMSGlobalConfigValues(t *testing.T) { t.Parallel() - checkSMSGlobalConfigValues := config.GetConfig() - err := checkSMSGlobalConfigValues.LoadConfig() + checkSMSGlobalConfigValues := GetConfig() + err := checkSMSGlobalConfigValues.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. checkSMSGlobalConfigValues.LoadConfig: %s", err) } @@ -71,8 +69,8 @@ func TestCheckSMSGlobalConfigValues(t *testing.T) { func TestCheckExchangeConfigValues(t *testing.T) { t.Parallel() - checkExchangeConfigValues := config.Config{} - err := checkExchangeConfigValues.LoadConfig() + checkExchangeConfigValues := Config{} + err := checkExchangeConfigValues.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. checkExchangeConfigValues.LoadConfig: %s", err.Error()) } @@ -86,8 +84,8 @@ func TestCheckExchangeConfigValues(t *testing.T) { func TestCheckWebserverConfigValues(t *testing.T) { t.Parallel() - checkWebserverConfigValues := config.GetConfig() - err := checkWebserverConfigValues.LoadConfig() + checkWebserverConfigValues := GetConfig() + err := checkWebserverConfigValues.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. checkWebserverConfigValues.LoadConfig: %s", err.Error()) } @@ -100,8 +98,8 @@ func TestCheckWebserverConfigValues(t *testing.T) { func TestRetrieveConfigCurrencyPairs(t *testing.T) { t.Parallel() - retrieveConfigCurrencyPairs := config.GetConfig() - err := retrieveConfigCurrencyPairs.LoadConfig() + retrieveConfigCurrencyPairs := GetConfig() + err := retrieveConfigCurrencyPairs.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. checkWebserverConfigValues.LoadConfig: %s", err.Error()) } @@ -114,8 +112,8 @@ func TestRetrieveConfigCurrencyPairs(t *testing.T) { func TestReadConfig(t *testing.T) { t.Parallel() - readConfig := config.GetConfig() - err := readConfig.ReadConfig() + readConfig := GetConfig() + err := readConfig.ReadConfig("../testdata/configtest.dat") if err != nil { t.Error("Test failed. TestReadConfig " + err.Error()) } @@ -124,22 +122,20 @@ func TestReadConfig(t *testing.T) { func TestLoadConfig(t *testing.T) { t.Parallel() - loadConfig := config.GetConfig() - err := loadConfig.LoadConfig() + loadConfig := GetConfig() + err := loadConfig.LoadConfig("../testdata/configtest.dat") if err != nil { t.Error("Test failed. TestLoadConfig " + err.Error()) } } func TestSaveConfig(t *testing.T) { - t.Parallel() - - saveConfig := config.GetConfig() - err := saveConfig.LoadConfig() + saveConfig := GetConfig() + err := saveConfig.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test failed. TestSaveConfig.LoadConfig: %s", err.Error()) } - err2 := saveConfig.SaveConfig() + err2 := saveConfig.SaveConfig("../testdata/configtest.dat") if err2 != nil { t.Error("Test failed. TestSaveConfig.SaveConfig, %s", err2.Error()) } diff --git a/config/config_tests/config_example.dat b/config/config_tests/config_example.dat deleted file mode 100644 index 973ffa04..00000000 --- a/config/config_tests/config_example.dat +++ /dev/null @@ -1,287 +0,0 @@ -{ - "Name": "Skynet", - "EncryptConfig": 0, - "Cryptocurrencies": "BTC,LTC,ETH,XRP,NMC,NVC,PPC,XBT,DOGE,DASH", - "PortfolioAddresses": { - "Addresses": [ - { - "Address": "1JCe8z4jJVNXSjohjM4i9Hh813dLCNx2Sy", - "CoinType": "BTC", - "Balance": 124178.0002442 - }, - { - "Address": "3Nxwenay9Z8Lc9JBiywExpnEFiLp6Afp8v", - "CoinType": "BTC", - "Balance": 103439.83659727 - }, - { - "Address": "LgY8ahfHRhvjVQC1zJnBhFMG5pCTMuKRqh", - "CoinType": "LTC", - "Balance": 3.00000005e+06 - }, - { - "Address": "0xb794f5ea0ba39494ce839613fffba74279579268", - "CoinType": "ETH", - "Balance": 5.774999820458524e+06 - } - ] - }, - "SMSGlobal": { - "Enabled": false, - "Username": "Username", - "Password": "Password", - "Contacts": [ - { - "Name": "Bob", - "Number": "12345", - "Enabled": false - } - ] - }, - "Webserver": { - "Enabled": false, - "AdminUsername": "admin", - "AdminPassword": "Password", - "ListenAddress": ":9050" - }, - "Exchanges": [ - { - "Name": "ANX", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", - "EnabledPairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", - "BaseCurrencies": "USD,HKD,EUR,CAD,AUD,SGD,JPY,GBP,NZD" - }, - { - "Name": "Bitfinex", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC,ETCBTC,ETCUSD,BFXUSD,BFXBTC,RRTUSD,RRTBTC,ZECUSD,ZECBTC,XMRUSD,XMRBTC,DSHUSD,DSHBTC", - "EnabledPairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC", - "BaseCurrencies": "USD" - }, - { - "Name": "Bitstamp", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "ClientID", - "AvailablePairs": "BTCUSD,BTCEUR,EURUSD,XRPUSD,XRPEUR", - "EnabledPairs": "BTCUSD,BTCEUR,EURUSD,XRPUSD,XRPEUR", - "BaseCurrencies": "USD,EUR" - }, - { - "Name": "BTCC", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCCNY,LTCCNY,LTCBTC", - "EnabledPairs": "BTCCNY,LTCCNY,LTCBTC", - "BaseCurrencies": "CNY" - }, - { - "Name": "BTCE", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", - "EnabledPairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", - "BaseCurrencies": "USD,RUR,EUR" - }, - { - "Name": "BTC Markets", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "LTC,BTC", - "EnabledPairs": "LTC,BTC", - "BaseCurrencies": "AUD" - }, - { - "Name": "GDAX", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "ClientID", - "AvailablePairs": "BTCGBP,BTCEUR,ETHUSD,ETHBTC,LTCUSD,LTCBTC,BTCUSD", - "EnabledPairs": "BTCUSD,BTCGBP,BTCEUR", - "BaseCurrencies": "USD,GBP,EUR" - }, - { - "Name": "Gemini", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCUSD,ETHBTC,ETHUSD", - "EnabledPairs": "BTCUSD", - "BaseCurrencies": "USD" - }, - { - "Name": "Huobi", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCCNY,LTCCNY", - "EnabledPairs": "BTCCNY,LTCCNY", - "BaseCurrencies": "CNY" - }, - { - "Name": "ITBIT", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "ClientID", - "AvailablePairs": "XBTUSD,XBTSGD,XBTEUR", - "EnabledPairs": "XBTUSD,XBTSGD,XBTEUR", - "BaseCurrencies": "USD,SGD,EUR" - }, - { - "Name": "Kraken", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "ETCUSD,ICNETH,REPXBT,ZECXBT,ETHXBT,ETHXBT.d,ETHGBP,LTCXBT,XBTGBP.d,XDGXBT,XMRUSD,ZECUSD,ETCETH,ETHJPY,XBTCAD.d,XBTJPY.d,XBTUSD.d,XLMXBT,XLMEUR,XLMUSD,XMREUR,ETCXBT,ETHCAD.d,ETHEUR.d,ETHJPY.d,XBTEUR.d,ETHEUR,ETHGBP.d,ICNXBT,LTCEUR,REPEUR,XBTGBP,XBTJPY,ETHUSD,ETHUSD.d,LTCUSD,REPETH,XBTUSD,XMRXBT,ETCEUR,ETHCAD,REPUSD,XBTCAD,XBTEUR,XRPXBT,ZECEUR", - "EnabledPairs": "ETCUSD,XBTUSD,ETHUSD", - "BaseCurrencies": "EUR,USD,CAD,GBP,JPY" - }, - { - "Name": "LakeBTC", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCUSD,BTCEUR,USDHKD,AUDUSD,BTCGBP,BTCNZD,USDJPY,BTCSGD,BTCNGN,EURUSD,USDSGD,NZDUSD,USDNGN,USDCHF,BTCJPY,BTCAUD,BTCCAD,BTCCHF,GBPUSD,USDCAD", - "EnabledPairs": "BTCUSD,BTCAUD", - "BaseCurrencies": "USD,EUR,HKD,AUD,GBP,NZD,JPY,SGD,NGN,CHF,CAD" - }, - { - "Name": "Liqui", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "TIME_BTC,ETH_BTC,GNT_BTC,WAVES_BTC,ICN_BTC,1ST_BTC,WINGS_BTC,MLN_BTC,ROUND_BTC,VSL_BTC,LTC_BTC,DCT_BTC,INCNT_BTC,PLU_BTC,DASH_BTC", - "EnabledPairs": "ETH_BTC,LTC_BTC,DASH_BTC", - "BaseCurrencies": "USD" - }, - { - "Name": "LocalBitcoins", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", - "EnabledPairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", - "BaseCurrencies": "ARS,AUD,BRL,CAD,CHF,CZK,DKK,EUR,GBP,HKD,ILS,INR,MXN,NOK,NZD,PLN,RUB,SEK,SGD,THB,USD,ZAR" - }, - { - "Name": "OKCOIN China", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCCNY,LTCCNY", - "EnabledPairs": "BTCCNY,LTCCNY", - "BaseCurrencies": "CNY" - }, - { - "Name": "OKCOIN International", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTCUSD,LTCUSD", - "EnabledPairs": "BTCUSD,LTCUSD", - "BaseCurrencies": "USD" - }, - { - "Name": "Poloniex", - "Enabled": true, - "Verbose": false, - "Websocket": false, - "RESTPollingDelay": 10, - "AuthenticatedAPISupport": false, - "APIKey": "Key", - "APISecret": "Secret", - "ClientID": "", - "AvailablePairs": "BTC_XUSD,BTC_FCT,BTC_MMNXT,BTC_NMC,BTC_BITUSD,BTC_RDD,BTC_XMR,BTC_XST,BTC_DSH,BTC_MAID,BTC_DGB,BTC_NEOS,BTC_BLK,BTC_NAUT,BTC_NBT,BTC_XCP,BTC_STR,BTC_BTCD,BTC_GRC,BTC_HUC,BTC_BBR,BTC_XDN,BTC_INDEX,BTC_IOC,BTC_SWARM,BTC_EMC2,BTC_MCN,BTC_NOXT,BTC_MINT,BTC_PTS,BTC_SC,BTC_GEO,BTC_XRP,BTC_FLO,BTC_BITS,BTC_HYP,BTC_XCR,BTC_LTBC,BTC_SYS,BTC_GMC,BTC_ETH,BTC_SYNC,BTC_GAP,BTC_BCN,BTC_C2,BTC_PINK,BTC_FIBRE,BTC_POT,BTC_QTL,BTC_SDC,BTC_XC,BTC_DASH,BTC_SILK,BTC_CLAM,BTC_NAV,BTC_PIGGY,BTC_BCY,BTC_MIL,BTC_XCN,BTC_YACC,BTC_BTS,BTC_QBK,BTC_SJCX,BTC_LQD,BTC_BURST,BTC_RIC,BTC_VRC,BTC_LTC,BTC_XPB,BTC_GRS,BTC_XCH,BTC_ARCH,BTC_QORA,BTC_HZ,BTC_NSR,BTC_XPM,BTC_BITCNY,BTC_EXE,BTC_XMG,BTC_BTC,BTC_BTM,BTC_NOBL,BTC_NXT,BTC_DOGE,BTC_CURE,BTC_MNTA,BTC_ADN,BTC_EXP,BTC_VTC,BTC_FLDC,BTC_MRS,BTC_MYR,BTC_OMNI,BTC_VNL,BTC_USDT,BTC_NOTE,BTC_WDC,BTC_BELA,BTC_VIA,BTC_CGA,BTC_DIEM,BTC_IFC,BTC_XDP,BTC_BLOCK,BTC_MMC,BTC_1CR,BTC_UNITY,BTC_XBC,BTC_GEMZ,BTC_FLT,BTC_PPC,BTC_XEM,BTC_RBY,BTC_CNMT,BTC_ABY,XMR_XDN,XMR_IFC,XMR_DIEM,XMR_BBR,XMR_DSH,XMR_BCN,XMR_LTC,XMR_MAID,XMR_DASH,XMR_BTCD,XMR_HYP,XMR_BLK,XMR_QORA,XMR_MNTA,XMR_NXT,USDT_BTC,USDT_ETH,USDT_XRP,USDT_DASH,USDT_LTC,USDT_NXT,USDT_XMR,USDT_STR", - "EnabledPairs": "BTC_LTC,BTC_ETH,BTC_DOGE,BTC_DASH,BTC_XRP", - "BaseCurrencies": "USD" - } - ] -} \ No newline at end of file diff --git a/currency/currency_tests/currency_test.go b/currency/currency_test.go similarity index 73% rename from currency/currency_tests/currency_test.go rename to currency/currency_test.go index ca647382..340021cb 100644 --- a/currency/currency_tests/currency_test.go +++ b/currency/currency_test.go @@ -1,11 +1,10 @@ -package tests +package currency import ( "reflect" "testing" "github.com/thrasher-/gocryptotrader/common" - "github.com/thrasher-/gocryptotrader/currency" ) func TestIsDefaultCurrency(t *testing.T) { @@ -13,13 +12,13 @@ func TestIsDefaultCurrency(t *testing.T) { var str1, str2, str3 string = "USD", "usd", "cats123" - if !currency.IsDefaultCurrency(str1) { + if !IsDefaultCurrency(str1) { t.Errorf("Test Failed. TestIsDefaultCurrency: \nCannot match currency, %s.", str1) } - if !currency.IsDefaultCurrency(str2) { + if !IsDefaultCurrency(str2) { t.Errorf("Test Failed. TestIsDefaultCurrency: \nCannot match currency, %s.", str2) } - if currency.IsDefaultCurrency(str3) { + if IsDefaultCurrency(str3) { t.Errorf("Test Failed. TestIsDefaultCurrency: \nFunction return is incorrect with, %s.", str3) } } @@ -29,13 +28,13 @@ func TestIsDefaultCryptocurrency(t *testing.T) { var str1, str2, str3 string = "BTC", "btc", "dogs123" - if !currency.IsDefaultCryptocurrency(str1) { + if !IsDefaultCryptocurrency(str1) { t.Errorf("Test Failed. TestIsDefaultCryptocurrency: \nCannot match currency, %s.", str1) } - if !currency.IsDefaultCryptocurrency(str2) { + if !IsDefaultCryptocurrency(str2) { t.Errorf("Test Failed. TestIsDefaultCryptocurrency: \nCannot match currency, %s.", str2) } - if currency.IsDefaultCryptocurrency(str3) { + if IsDefaultCryptocurrency(str3) { t.Errorf("Test Failed. TestIsDefaultCryptocurrency: \nFunction return is incorrect with, %s.", str3) } } @@ -43,17 +42,16 @@ func TestIsDefaultCryptocurrency(t *testing.T) { func TestIsFiatCurrency(t *testing.T) { t.Parallel() - currency.BaseCurrencies = "USD,AUD" - + BaseCurrencies = "USD,AUD" var str1, str2, str3 string = "BTC", "USD", "birds123" - if currency.IsFiatCurrency(str1) { + if IsFiatCurrency(str1) { t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str1) } - if !currency.IsFiatCurrency(str2) { + if !IsFiatCurrency(str2) { t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str2) } - if currency.IsFiatCurrency(str3) { + if IsFiatCurrency(str3) { t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str3) } } @@ -61,16 +59,16 @@ func TestIsFiatCurrency(t *testing.T) { func TestIsCryptocurrency(t *testing.T) { t.Parallel() - currency.CryptoCurrencies = "BTC,LTC,DASH" + CryptoCurrencies = "BTC,LTC,DASH" var str1, str2, str3 string = "USD", "BTC", "pterodactyl123" - if currency.IsCryptocurrency(str1) { + if IsCryptocurrency(str1) { t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str1) } - if !currency.IsCryptocurrency(str2) { + if !IsCryptocurrency(str2) { t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str2) } - if currency.IsCryptocurrency(str3) { + if IsCryptocurrency(str3) { t.Errorf("Test Failed. TestIsFiatCurrency: \nCannot match currency, %s.", str3) } } @@ -80,19 +78,19 @@ func TestContainsSeparator(t *testing.T) { var str1, str2, str3, str4 string = "ding-dong", "ding_dong", "dong_ding-dang", "ding" - doesIt, whatIsIt := currency.ContainsSeparator(str1) + doesIt, whatIsIt := ContainsSeparator(str1) if doesIt != true || whatIsIt != "-" { t.Errorf("Test Failed. ContainsSeparator: \nCannot find separator, %s.", str1) } - doesIt2, whatIsIt2 := currency.ContainsSeparator(str2) + doesIt2, whatIsIt2 := ContainsSeparator(str2) if doesIt2 != true || whatIsIt2 != "_" { t.Errorf("Test Failed. ContainsSeparator: \nCannot find separator, %s.", str2) } - doesIt3, whatIsIt3 := currency.ContainsSeparator(str3) + doesIt3, whatIsIt3 := ContainsSeparator(str3) if doesIt3 != true || len(whatIsIt3) != 3 { t.Errorf("Test Failed. ContainsSeparator: \nCannot find or incorrect separator, %s.", str3) } - doesIt4, whatIsIt4 := currency.ContainsSeparator(str4) + doesIt4, whatIsIt4 := ContainsSeparator(str4) if doesIt4 != false || whatIsIt4 != "" { t.Errorf("Test Failed. ContainsSeparator: \nReturn Issues with string, %s.", str3) } @@ -104,11 +102,11 @@ func TestContainsBaseCurrencyIndex(t *testing.T) { baseCurrencies := []string{"USD", "AUD", "EUR", "CNY"} currency1, currency2 := "USD", "DINGDONG" - isIt, whatIsIt := currency.ContainsBaseCurrencyIndex(baseCurrencies, currency1) + isIt, whatIsIt := ContainsBaseCurrencyIndex(baseCurrencies, currency1) if !isIt && whatIsIt != "USD" { t.Errorf("Test Failed. ContainsBaseCurrencyIndex: \nReturned: %t & %s, with Currency as %s.", isIt, whatIsIt, currency1) } - isIt2, whatIsIt2 := currency.ContainsBaseCurrencyIndex(baseCurrencies, currency2) + isIt2, whatIsIt2 := ContainsBaseCurrencyIndex(baseCurrencies, currency2) if isIt2 && whatIsIt2 != "DINGDONG" { t.Errorf("Test Failed. ContainsBaseCurrencyIndex: \nReturned: %t & %s, with Currency as %s.", isIt2, whatIsIt2, currency2) } @@ -120,11 +118,11 @@ func TestContainsBaseCurrency(t *testing.T) { baseCurrencies := []string{"USD", "AUD", "EUR", "CNY"} currency1, currency2 := "USD", "DINGDONG" - isIt := currency.ContainsBaseCurrency(baseCurrencies, currency1) + isIt := ContainsBaseCurrency(baseCurrencies, currency1) if !isIt { t.Errorf("Test Failed. ContainsBaseCurrency: \nReturned: %t, with Currency as %s.", isIt, currency1) } - isIt2 := currency.ContainsBaseCurrency(baseCurrencies, currency2) + isIt2 := ContainsBaseCurrency(baseCurrencies, currency2) if isIt2 { t.Errorf("Test Failed. ContainsBaseCurrency: \nReturned: %t, with Currency as %s.", isIt2, currency2) } @@ -141,37 +139,37 @@ func TestCheckAndAddCurrency(t *testing.T) { cryptoIncrease := "XMR" obtuse := "CATSANDDOGS" - appendedString := currency.CheckAndAddCurrency(inputFiat, fiat) + appendedString := CheckAndAddCurrency(inputFiat, fiat) if len(appendedString) > len(inputFiat) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", fiat) } - appendedString = currency.CheckAndAddCurrency(inputFiat, fiatIncrease) + appendedString = CheckAndAddCurrency(inputFiat, fiatIncrease) if len(appendedString) <= len(inputFiat) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", fiatIncrease) } - appendedString = currency.CheckAndAddCurrency(inputFiat, crypto) + appendedString = CheckAndAddCurrency(inputFiat, crypto) if len(appendedString) > len(inputFiat) { t.Log(appendedString) t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", crypto) } - appendedString = currency.CheckAndAddCurrency(inputFiat, obtuse) + appendedString = CheckAndAddCurrency(inputFiat, obtuse) if len(appendedString) > len(inputFiat) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputFiat, currency as %s.", obtuse) } - appendedString = currency.CheckAndAddCurrency(inputCrypto, crypto) + appendedString = CheckAndAddCurrency(inputCrypto, crypto) if len(appendedString) > len(inputCrypto) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", crypto) } - appendedString = currency.CheckAndAddCurrency(inputCrypto, cryptoIncrease) + appendedString = CheckAndAddCurrency(inputCrypto, cryptoIncrease) if len(appendedString) <= len(inputCrypto) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", cryptoIncrease) } - appendedString = currency.CheckAndAddCurrency(inputCrypto, fiat) + appendedString = CheckAndAddCurrency(inputCrypto, fiat) if len(appendedString) > len(inputCrypto) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", fiat) } - appendedString = currency.CheckAndAddCurrency(inputCrypto, obtuse) + appendedString = CheckAndAddCurrency(inputCrypto, obtuse) if len(appendedString) > len(inputCrypto) { t.Errorf("Test Failed. CheckAndAddCurrency: Error with inputCrytpo, currency as %s.", obtuse) } @@ -184,15 +182,15 @@ func TestSeedCurrencyData(t *testing.T) { currencyRequestUSDAUD := "USD,AUD" currencyRequestObtuse := "WigWham" - err := currency.SeedCurrencyData(currencyRequestDefault) + err := SeedCurrencyData(currencyRequestDefault) if err != nil { t.Errorf("Test Failed. SeedCurrencyData: Error %s with currency as %s.", err, currencyRequestDefault) } - err2 := currency.SeedCurrencyData(currencyRequestUSDAUD) + err2 := SeedCurrencyData(currencyRequestUSDAUD) if err2 != nil { t.Errorf("Test Failed. SeedCurrencyData: Error %s with currency as %s.", err2, currencyRequestUSDAUD) } - err3 := currency.SeedCurrencyData(currencyRequestObtuse) + err3 := SeedCurrencyData(currencyRequestObtuse) if err3 == nil { t.Errorf("Test Failed. SeedCurrencyData: Error %s with currency as %s.", err3, currencyRequestObtuse) } @@ -201,8 +199,8 @@ func TestSeedCurrencyData(t *testing.T) { func TestMakecurrencyPairs(t *testing.T) { t.Parallel() - lengthDefault := len(common.SplitStrings(currency.DEFAULT_CURRENCIES, ",")) - fiatPairsLength := len(common.SplitStrings(currency.MakecurrencyPairs(currency.DEFAULT_CURRENCIES), ",")) + lengthDefault := len(common.SplitStrings(DEFAULT_CURRENCIES, ",")) + fiatPairsLength := len(common.SplitStrings(MakecurrencyPairs(DEFAULT_CURRENCIES), ",")) if lengthDefault*(lengthDefault-1) > fiatPairsLength { t.Error("Test Failed. MakecurrencyPairs: Error, mismatched length") @@ -212,13 +210,13 @@ func TestMakecurrencyPairs(t *testing.T) { func TestConvertCurrency(t *testing.T) { t.Parallel() - fiatCurrencies := currency.DEFAULT_CURRENCIES + fiatCurrencies := DEFAULT_CURRENCIES for _, currencyFrom := range common.SplitStrings(fiatCurrencies, ",") { for _, currencyTo := range common.SplitStrings(fiatCurrencies, ",") { if currencyFrom == currencyTo { continue } else { - floatyMcfloat, err := currency.ConvertCurrency(1000, currencyFrom, currencyTo) + floatyMcfloat, err := ConvertCurrency(1000, currencyFrom, currencyTo) if err != nil { t.Errorf("Test Failed. ConvertCurrency: Error %s with return: %.2f Currency 1: %s Currency 2: %s", err, floatyMcfloat, currencyFrom, currencyTo) @@ -237,7 +235,7 @@ func TestConvertCurrency(t *testing.T) { func TestFetchYahooCurrencyData(t *testing.T) { t.Parallel() var fetchData []string - fiatCurrencies := currency.DEFAULT_CURRENCIES + fiatCurrencies := DEFAULT_CURRENCIES for _, currencyOne := range common.SplitStrings(fiatCurrencies, ",") { for _, currencyTwo := range common.SplitStrings(fiatCurrencies, ",") { @@ -248,7 +246,7 @@ func TestFetchYahooCurrencyData(t *testing.T) { } } } - err := currency.FetchYahooCurrencyData(fetchData) + err := FetchYahooCurrencyData(fetchData) if err != nil { t.Errorf("Test Failed. FetchYahooCurrencyData: Error %s", err) } @@ -257,12 +255,12 @@ func TestFetchYahooCurrencyData(t *testing.T) { func TestQueryYahooCurrencyValues(t *testing.T) { t.Parallel() - err := currency.QueryYahooCurrencyValues(currency.DEFAULT_CURRENCIES) + err := QueryYahooCurrencyValues(DEFAULT_CURRENCIES) if err != nil { t.Errorf("Test Failed. QueryYahooCurrencyValues: Error, %s", err) } - err2 := currency.QueryYahooCurrencyValues(currency.DEFAULT_CRYPTOCURRENCIES) + err2 := QueryYahooCurrencyValues(DEFAULT_CRYPTOCURRENCIES) if err2 == nil { t.Errorf("Test Failed. QueryYahooCurrencyValues: Error, %s", err2) } diff --git a/events/event_tests/event_test.go b/events/event_test.go similarity index 62% rename from events/event_tests/event_test.go rename to events/event_test.go index 041baebc..8bc486ea 100644 --- a/events/event_tests/event_test.go +++ b/events/event_test.go @@ -1,82 +1,79 @@ -package tests +package events import ( "testing" - - "github.com/thrasher-/gocryptotrader/events" ) func TestAddEvent(t *testing.T) { - eventID, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + eventID, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil && eventID != 0 { t.Errorf("Test Failed. AddEvent: Error, %s", err) } - eventID, err = events.AddEvent("ANXX", "price", ">,==", "BTC", "LTC", "console_print") + eventID, err = AddEvent("ANXX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err == nil && eventID == 0 { t.Error("Test Failed. AddEvent: Error, error not captured in Exchange") } - eventID, err = events.AddEvent("ANX", "prices", ">,==", "BTC", "LTC", "console_print") + eventID, err = AddEvent("ANX", "prices", ">,==", "BTC", "LTC", ACTION_TEST) if err == nil && eventID == 0 { t.Error("Test Failed. AddEvent: Error, error not captured in Item") } - eventID, err = events.AddEvent("ANX", "price", "3===D", "BTC", "LTC", "console_print") + eventID, err = AddEvent("ANX", "price", "3===D", "BTC", "LTC", ACTION_TEST) if err == nil && eventID == 0 { t.Error("Test Failed. AddEvent: Error, error not captured in Condition") } - eventID, err = events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_prints") + eventID, err = AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_prints") if err == nil && eventID == 0 { t.Error("Test Failed. AddEvent: Error, error not captured in Action") } - eventID, err = events.AddEvent("ANX", "price", ">,==", "BATMAN", "ROBIN", "console_print") + eventID, err = AddEvent("ANX", "price", ">,==", "BATMAN", "ROBIN", ACTION_TEST) if err == nil && eventID == 0 { t.Error("Test Failed. AddEvent: Error, error not captured in Action") } - if !events.RemoveEvent(eventID) { + if !RemoveEvent(eventID) { t.Error("Test Failed. RemoveEvent: Error, error removing event") } } func TestRemoveEvent(t *testing.T) { - eventID, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + eventID, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil && eventID != 0 { t.Errorf("Test Failed. RemoveEvent: Error, %s", err) } - if !events.RemoveEvent(eventID) { + if !RemoveEvent(eventID) { t.Error("Test Failed. RemoveEvent: Error, error removing event") } } func TestGetEventCounter(t *testing.T) { - one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + one, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil { t.Errorf("Test Failed. GetEventCounter: Error, %s", err) } - two, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + two, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil { t.Errorf("Test Failed. GetEventCounter: Error, %s", err) } - three, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + three, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil { t.Errorf("Test Failed. GetEventCounter: Error, %s", err) } - total, _ := events.GetEventCounter() + total, _ := GetEventCounter() if total <= 0 { t.Errorf("Test Failed. GetEventCounter: Total = %d", total) } - if !events.RemoveEvent(one) { + if !RemoveEvent(one) { t.Error("Test Failed. GetEventCounter: Error, error removing event") } - if !events.RemoveEvent(two) { + if !RemoveEvent(two) { t.Error("Test Failed. GetEventCounter: Error, error removing event") } - if !events.RemoveEvent(three) { + if !RemoveEvent(three) { t.Error("Test Failed. GetEventCounter: Error, error removing event") } - total2, _ := events.GetEventCounter() - t.Log(total2) + total2, _ := GetEventCounter() if total2 != 0 { t.Errorf("Test Failed. GetEventCounter: Total = %d", total2) } @@ -85,16 +82,16 @@ func TestGetEventCounter(t *testing.T) { func TestExecuteAction(t *testing.T) { t.Parallel() - one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + one, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil { t.Errorf("Test Failed. ExecuteAction: Error, %s", err) } - isExecuted := events.Events[one].ExecuteAction() + isExecuted := Events[one].ExecuteAction() if !isExecuted { t.Error("Test Failed. ExecuteAction: Error, error removing event") } - if !events.RemoveEvent(one) { + if !RemoveEvent(one) { t.Error("Test Failed. ExecuteAction: Error, error removing event") } } @@ -102,17 +99,17 @@ func TestExecuteAction(t *testing.T) { func TestEventToString(t *testing.T) { t.Parallel() - one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + one, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil { t.Errorf("Test Failed. EventToString: Error, %s", err) } - eventString := events.Events[one].EventToString() - if eventString != "If the BTCLTC price on ANX is > == then console_print." { + eventString := Events[one].EventToString() + if eventString != "If the BTCLTC price on ANX is > == then ACTION_TEST." { t.Error("Test Failed. EventToString: Error, incorrect return string") } - if !events.RemoveEvent(one) { + if !RemoveEvent(one) { t.Error("Test Failed. EventToString: Error, error removing event") } @@ -121,39 +118,39 @@ func TestEventToString(t *testing.T) { func TestCheckCondition(t *testing.T) { //error handling needs to be implemented t.Parallel() - one, err := events.AddEvent("ANX", "price", ">,==", "BTC", "LTC", "console_print") + one, err := AddEvent("ANX", "price", ">,==", "BTC", "LTC", ACTION_TEST) if err != nil { t.Errorf("Test Failed. EventToString: Error, %s", err) } - conditionBool := events.Events[one].CheckCondition() + conditionBool := Events[one].CheckCondition() if conditionBool { //check once error handling is implemented t.Error("Test Failed. EventToString: Error, wrong conditional.") } - if !events.RemoveEvent(one) { + if !RemoveEvent(one) { t.Error("Test Failed. EventToString: Error, error removing event") } } func TestIsValidEvent(t *testing.T) { - err := events.IsValidEvent("ANX", "price", ">,==", "console_print") + err := IsValidEvent("ANX", "price", ">,==", ACTION_TEST) if err != nil { t.Errorf("Test Failed. IsValidExchange: Error %s", err) } } func TestCheckEvents(t *testing.T) { //Add error handling - //events.CheckEvents() //check once error handling is implemented + //CheckEvents() //check once error handling is implemented } func TestIsValidExchange(t *testing.T) { - boolean := events.IsValidExchange("ANX") + boolean := IsValidExchange("ANX", CONFIG_PATH_TEST) if !boolean { t.Error("Test Failed. IsValidExchange: Error, incorrect Exchange") } - boolean = events.IsValidExchange("OBTUSE") + boolean = IsValidExchange("OBTUSE", CONFIG_PATH_TEST) if boolean { t.Error("Test Failed. IsValidExchange: Error, incorrect return") } @@ -162,27 +159,27 @@ func TestIsValidExchange(t *testing.T) { func TestIsValidCondition(t *testing.T) { t.Parallel() - boolean := events.IsValidCondition(">") + boolean := IsValidCondition(">") if !boolean { t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") } - boolean = events.IsValidCondition(">=") + boolean = IsValidCondition(">=") if !boolean { t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") } - boolean = events.IsValidCondition("<") + boolean = IsValidCondition("<") if !boolean { t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") } - boolean = events.IsValidCondition("<=") + boolean = IsValidCondition("<=") if !boolean { t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") } - boolean = events.IsValidCondition("==") + boolean = IsValidCondition("==") if !boolean { t.Error("Test Failed. IsValidCondition: Error, incorrect Condition") } - boolean = events.IsValidCondition("**********") + boolean = IsValidCondition("**********") if boolean { t.Error("Test Failed. IsValidCondition: Error, incorrect return") } @@ -191,15 +188,15 @@ func TestIsValidCondition(t *testing.T) { func TestIsValidAction(t *testing.T) { t.Parallel() - boolean := events.IsValidAction("sms") + boolean := IsValidAction("sms") if !boolean { t.Error("Test Failed. IsValidAction: Error, incorrect Action") } - boolean = events.IsValidAction("console_print") + boolean = IsValidAction(ACTION_TEST) if !boolean { t.Error("Test Failed. IsValidAction: Error, incorrect Action") } - boolean = events.IsValidAction("randomstring") + boolean = IsValidAction("randomstring") if boolean { t.Error("Test Failed. IsValidAction: Error, incorrect return") } @@ -208,11 +205,11 @@ func TestIsValidAction(t *testing.T) { func TestIsValidItem(t *testing.T) { t.Parallel() - boolean := events.IsValidItem("price") + boolean := IsValidItem("price") if !boolean { t.Error("Test Failed. IsValidItem: Error, incorrect Item") } - boolean = events.IsValidItem("obtuse") + boolean = IsValidItem("obtuse") if boolean { t.Error("Test Failed. IsValidItem: Error, incorrect return") } diff --git a/events/events.go b/events/events.go index d0dc885f..3128b325 100644 --- a/events/events.go +++ b/events/events.go @@ -22,6 +22,8 @@ const ( IS_EQUAL = "==" ACTION_SMS_NOTIFY = "SMS" ACTION_CONSOLE_PRINT = "CONSOLE_PRINT" + ACTION_TEST = "ACTION_TEST" + CONFIG_PATH_TEST = "../testdata/configtest.dat" ) var ( @@ -174,7 +176,12 @@ func IsValidEvent(Exchange, Item, Condition, Action string) error { Item = common.StringToUpper(Item) Action = common.StringToUpper(Action) - if !IsValidExchange(Exchange) { + configPath := "" + if Action == ACTION_TEST { + configPath = CONFIG_PATH_TEST + } + + if !IsValidExchange(Exchange, configPath) { return ErrExchangeDisabled } @@ -203,7 +210,7 @@ func IsValidEvent(Exchange, Item, Condition, Action string) error { return ErrInvalidAction } } else { - if Action != ACTION_CONSOLE_PRINT { + if Action != ACTION_CONSOLE_PRINT && Action != ACTION_TEST { return ErrInvalidAction } } @@ -240,12 +247,12 @@ func IsValidCurrency(currencies ...string) bool { return false } -func IsValidExchange(Exchange string) bool { +func IsValidExchange(Exchange, configPath string) bool { Exchange = common.StringToUpper(Exchange) cfg := config.GetConfig() if len(cfg.Exchanges) == 0 { - cfg.LoadConfig() + cfg.LoadConfig(configPath) } for _, x := range cfg.Exchanges { @@ -267,7 +274,7 @@ func IsValidCondition(Condition string) bool { func IsValidAction(Action string) bool { Action = common.StringToUpper(Action) switch Action { - case ACTION_SMS_NOTIFY, ACTION_CONSOLE_PRINT: + case ACTION_SMS_NOTIFY, ACTION_CONSOLE_PRINT, ACTION_TEST: return true } return false diff --git a/exchanges/alphapoint/alphapoint.go b/exchanges/alphapoint/alphapoint.go index 761c6b39..510e1f96 100644 --- a/exchanges/alphapoint/alphapoint.go +++ b/exchanges/alphapoint/alphapoint.go @@ -137,6 +137,10 @@ func (a *Alphapoint) GetProducts() (AlphapointProducts, error) { } func (a *Alphapoint) CreateAccount(firstName, lastName, email, phone, password string) error { + if len(password) < 8 { + return errors.New("Alphapoint Error - Create account - Password must be 8 characters or more.") + } + request := make(map[string]interface{}) request["firstname"] = firstName request["lastname"] = lastName @@ -390,7 +394,6 @@ func (a *Alphapoint) SendRequest(method, path string, data map[string]interface{ if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") } - resp, err := common.SendHTTPRequest(method, path, headers, bytes.NewBuffer(PayloadJson)) if err != nil { diff --git a/exchanges/alphapoint/alphapoint_test.go b/exchanges/alphapoint/alphapoint_test.go new file mode 100644 index 00000000..91eef2a5 --- /dev/null +++ b/exchanges/alphapoint/alphapoint_test.go @@ -0,0 +1,413 @@ +package alphapoint + +import ( + "reflect" + "testing" +) + +func TestSetDefaults(t *testing.T) { + t.Parallel() + SetDefaults := Alphapoint{} + + SetDefaults.SetDefaults() + if SetDefaults.APIUrl != "https://sim3.alphapoint.com:8400" { + t.Error("Test Failed - SetDefaults: String Incorrect -", SetDefaults.APIUrl) + } + if SetDefaults.WebsocketURL != "wss://sim3.alphapoint.com:8401/v1/GetTicker/" { + t.Error("Test Failed - SetDefaults: String Incorrect -", SetDefaults.WebsocketURL) + } +} + +func TestGetTicker(t *testing.T) { + GetTicker := Alphapoint{} + GetTicker.SetDefaults() + + response, err := GetTicker.GetTicker("BTCUSD") + if err != nil { + t.Error("Test Failed - Alphapoint GetTicker init error: ", err) + } + if reflect.ValueOf(response).NumField() != 13 { + t.Error("Test Failed - Alphapoint GetTicker struct change/or updated") + } + if reflect.TypeOf(response.Ask).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Ask value is not a float64") + } + if reflect.TypeOf(response.Bid).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Bid value is not a float64") + } + if reflect.TypeOf(response.BuyOrderCount).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.BuyOrderCount value is not a float64") + } + if reflect.TypeOf(response.High).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.High value is not a float64") + } + if reflect.TypeOf(response.IsAccepted).String() != "bool" { + t.Error("Test Failed - Alphapoint GetTicker.IsAccepted value is not a bool") + } + if reflect.TypeOf(response.Last).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Last value is not a float64") + } + if reflect.TypeOf(response.Low).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Low value is not a float64") + } + if reflect.TypeOf(response.NumOfCreateOrders).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.NumOfCreateOrders value is not a float64") + } + if reflect.TypeOf(response.RejectReason).String() != "string" { + t.Error("Test Failed - Alphapoint GetTicker.RejectReason value is not a string") + } + if reflect.TypeOf(response.SellOrderCount).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.SellOrderCount value is not a float64") + } + if reflect.TypeOf(response.Total24HrNumTrades).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Total24HrNumTrades value is not a float64") + } + if reflect.TypeOf(response.Total24HrQtyTraded).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Total24HrQtyTraded value is not a float64") + } + if reflect.TypeOf(response.Volume).String() != "float64" { + t.Error("Test Failed - Alphapoint GetTicker.Volume value is not a float64") + } + + if response.Ask < 0 { + t.Error("Test Failed - Alphapoint GetTicker.Ask value is negative") + } + if response.Bid < 0 { + t.Error("Test Failed - Alphapoint GetTicker.Bid value is negative") + } + if response.BuyOrderCount < 0 { + t.Error("Test Failed - Alphapoint GetTicker.High value is negative") + } + if response.High < 0 { + t.Error("Test Failed - Alphapoint GetTicker.Last value is negative") + } + if response.Last < 0 { + t.Error("Test Failed - Alphapoint GetTicker.Low value is negative") + } + if response.Low < 0 { + t.Error("Test Failed - Alphapoint GetTicker.Mid value is negative") + } + if response.NumOfCreateOrders < 0 { + t.Error("Test Failed - Alphapoint GetTicker.ask value is negative") + } + if response.SellOrderCount < 0 { + t.Error("Test Failed - Alphapoint GetTicker.ask value is negative") + } + if response.Total24HrNumTrades < 0 { + t.Error("Test Failed - Alphapoint GetTicker.ask value is negative") + } + if response.Total24HrQtyTraded < 0 { + t.Error("Test Failed - Alphapoint GetTicker.ask value is negative") + } + if response.Volume < 0 { + t.Error("Test Failed - Alphapoint GetTicker.ask value is negative") + } +} + +func TestGetTrades(t *testing.T) { + GetTrades := Alphapoint{} + GetTrades.SetDefaults() + + trades, err := GetTrades.GetTrades("BTCUSD", 0, 10) + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } + if reflect.ValueOf(trades).NumField() != 7 { + t.Error("Test Failed - Alphapoint AlphapointTrades struct updated/changed") + } + if len(trades.Trades) == 0 { + t.Error("Test Failed - Alphapoint trades.Trades: Incorrect length") + } + if reflect.ValueOf(trades.Trades[0]).NumField() != 8 { + t.Error("Test Failed - Alphapoint AlphapointTrades.Trades struct updated/changed") + } + if reflect.TypeOf(trades.Trades[0].BookServerOrderID).String() != "int" { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is not a int") + } + if reflect.TypeOf(trades.Trades[0].IncomingOrderSide).String() != "int" { + t.Error("Test Failed - Alphapoint trades.Trades.IncomingOrderSide value is not a int") + } + if reflect.TypeOf(trades.Trades[0].IncomingServerOrderID).String() != "int" { + t.Error("Test Failed - Alphapoint trades.Trades.IncomingServerOrderID value is not a int") + } + if reflect.TypeOf(trades.Trades[0].Price).String() != "float64" { + t.Error("Test Failed - Alphapoint trades.Trades.Price value is not a float64") + } + if reflect.TypeOf(trades.Trades[0].Quantity).String() != "float64" { + t.Error("Test Failed - Alphapoint trades.Trades.Quantity value is not a float64") + } + if reflect.TypeOf(trades.Trades[0].TID).String() != "int64" { + t.Error("Test Failed - Alphapoint trades.Trades.TID value is not a int64") + } + if reflect.TypeOf(trades.Trades[0].UTCTicks).String() != "int64" { + t.Error("Test Failed - Alphapoint trades.Trades.UTCTicks value is not a int64") + } + if reflect.TypeOf(trades.Trades[0].Unixtime).String() != "int" { + t.Error("Test Failed - Alphapoint trades.Trades.Unixtime value is not a int") + } + if reflect.TypeOf(trades.Count).String() != "int" { + t.Error("Test Failed - Alphapoint trades.Count value is not a int") + } + if reflect.TypeOf(trades.DateTimeUTC).String() != "int64" { + t.Error("Test Failed - Alphapoint trades.DateTimeUTC value is not a int64") + } + if reflect.TypeOf(trades.Instrument).String() != "string" { + t.Error("Test Failed - Alphapoint trades.Instrument value is not a string") + } + if reflect.TypeOf(trades.IsAccepted).String() != "bool" { + t.Error("Test Failed - Alphapoint trades.IsAccepted value is not a bool") + } + if reflect.TypeOf(trades.RejectReason).String() != "string" { + t.Error("Test Failed - Alphapoint trades.string value is not a string") + } + if reflect.TypeOf(trades.StartIndex).String() != "int" { + t.Error("Test Failed - Alphapoint trades.Count value is not a int") + } + + if trades.Count < 0 { + t.Error("Test Failed - Alphapoint trades.Count value is negative") + } + if trades.DateTimeUTC <= 0 { + t.Error("Test Failed - Alphapoint trades.DateTimeUTC value is negative or 0") + } + if trades.Instrument != "BTCUSD" { + t.Error("Test Failed - Alphapoint trades.Instrument value is incorrect") + } + if trades.IsAccepted != true { + t.Error("Test Failed - Alphapoint trades.IsAccepted value is true") + } + if len(trades.RejectReason) > 0 { + t.Error("Test Failed - Alphapoint trades.IsAccepted value has been returned") + } + if trades.StartIndex != 0 { + t.Error("Test Failed - Alphapoint trades.StartIndex value is incorrect") + } + if trades.Trades[0].BookServerOrderID < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].IncomingOrderSide < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].IncomingServerOrderID < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].Price < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].Quantity < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].TID != 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].UTCTicks < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } + if trades.Trades[0].Unixtime < 0 { + t.Error("Test Failed - Alphapoint trades.Trades.BookServerOrderID value is negative") + } +} + +func TestGetTradesByDate(t *testing.T) { + GetTradesByDate := Alphapoint{} + GetTradesByDate.SetDefaults() + + trades, err := GetTradesByDate.GetTradesByDate("BTCUSD", 1414799400, 1414800000) + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } + if reflect.ValueOf(trades).NumField() != 7 { + t.Error("Test Failed - Alphapoint AlphapointTrades struct updated/changed") + } + if len(trades.Trades) != 0 { + t.Error("Test Failed - Alphapoint trades.Trades: Incorrect length") + } + if reflect.TypeOf(trades.DateTimeUTC).String() != "int64" { + t.Error("Test Failed - Alphapoint trades.Count value is not a int64") + } + if reflect.TypeOf(trades.EndDate).String() != "int64" { + t.Error("Test Failed - Alphapoint trades.DateTimeUTC value is not a int64") + } + if reflect.TypeOf(trades.Instrument).String() != "string" { + t.Error("Test Failed - Alphapoint trades.Instrument value is not a string") + } + if reflect.TypeOf(trades.IsAccepted).String() != "bool" { + t.Error("Test Failed - Alphapoint trades.IsAccepted value is not a bool") + } + if reflect.TypeOf(trades.RejectReason).String() != "string" { + t.Error("Test Failed - Alphapoint trades.string value is not a string") + } + if reflect.TypeOf(trades.StartDate).String() != "int64" { + t.Error("Test Failed - Alphapoint trades.StartDate value is not a int64") + } + + if trades.DateTimeUTC < 0 { + t.Error("Test Failed - Alphapoint trades.Count value is negative") + } + if trades.EndDate < 0 { + t.Error("Test Failed - Alphapoint trades.DateTimeUTC value is negative") + } + if trades.Instrument != "BTCUSD" { + t.Error("Test Failed - Alphapoint trades.Instrument value is incorrect") + } + if trades.IsAccepted != true { + t.Error("Test Failed - Alphapoint trades.IsAccepted value is true") + } + if len(trades.RejectReason) > 0 { + t.Error("Test Failed - Alphapoint trades.IsAccepted value has been returned") + } + if trades.StartDate < 0 { + t.Error("Test Failed - Alphapoint trades.StartIndex value is negative") + } +} + +func TestGetOrderbook(t *testing.T) { + GetOrderbook := Alphapoint{} + GetOrderbook.SetDefaults() + + orderBook, err := GetOrderbook.GetOrderbook("BTCUSD") + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } + if reflect.ValueOf(orderBook).NumField() != 4 { + t.Error("Test Failed - Alphapoint AlphapointOrderbook struct updated/changed") + } + if reflect.TypeOf(orderBook.IsAccepted).String() != "bool" { + t.Error("Test Failed - Alphapoint orderBook.IsAccepted value is not a bool") + } + if reflect.TypeOf(orderBook.RejectReason).String() != "string" { + t.Error("Test Failed - Alphapoint orderBook.RejectReason value is not a string") + } + if len(orderBook.Asks) < 1 { + t.Error("Test Failed - Alphapoint orderBook.Asks does not contain anything.") + } + if len(orderBook.Bids) < 1 { + t.Error("Test Failed - Alphapoint orderBook.Asks does not contain anything.") + } +} + +func TestGetProductPairs(t *testing.T) { + GetProductPairs := Alphapoint{} + GetProductPairs.SetDefaults() + + productPairs, err := GetProductPairs.GetProductPairs() + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } + if reflect.ValueOf(productPairs).NumField() != 3 { + t.Error("Test Failed - Alphapoint GetProductPairs struct updated/changed") + } + if reflect.TypeOf(productPairs.IsAccepted).String() != "bool" { + t.Error("Test Failed - Alphapoint productPairs.IsAccepted value is not a bool") + } + if reflect.TypeOf(productPairs.RejectReason).String() != "string" { + t.Error("Test Failed - Alphapoint productPairs.RejectReason value is not a string") + } + + if len(productPairs.ProductPairs) >= 1 { + if reflect.ValueOf(productPairs.ProductPairs[0]).NumField() != 6 { + t.Error("Test Failed - Alphapoint GetProductPairs.ProductPairs[] struct updated/changed") + } + if reflect.TypeOf(productPairs.ProductPairs[0].Name).String() != "string" { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Name value is not a string") + } + if reflect.TypeOf(productPairs.ProductPairs[0].Product1Decimalplaces).String() != "int" { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Product1Decimalplaces value is not a int") + } + if reflect.TypeOf(productPairs.ProductPairs[0].Product1Label).String() != "string" { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Product1Label value is not a string") + } + if reflect.TypeOf(productPairs.ProductPairs[0].Product2Decimalplaces).String() != "int" { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Product2Decimalplaces value is not a int") + } + if reflect.TypeOf(productPairs.ProductPairs[0].Product2Label).String() != "string" { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Product2Label value is not a string") + } + if reflect.TypeOf(productPairs.ProductPairs[0].Productpaircode).String() != "int" { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Productpaircode value is not a int") + } + + if productPairs.ProductPairs[0].Product1Decimalplaces < 0 { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Product1Decimalplaces value is negative") + } + if productPairs.ProductPairs[0].Product2Decimalplaces < 0 { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Product2Decimalplaces value is negative") + } + if productPairs.ProductPairs[0].Productpaircode < 0 { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs.Productpaircode value is negative") + } + } else { + t.Error("Test Failed - Alphapoint productPairs.ProductPairs no product pairs.") + } +} + +func TestGetProducts(t *testing.T) { + GetProducts := Alphapoint{} + GetProducts.SetDefaults() + + products, err := GetProducts.GetProducts() + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } + if reflect.ValueOf(products).NumField() != 3 { + t.Error("Test Failed - Alphapoint GetProductPairs struct updated/changed") + } + if reflect.TypeOf(products.IsAccepted).String() != "bool" { + t.Error("Test Failed - Alphapoint products.IsAccepted value is not a bool") + } + if reflect.TypeOf(products.RejectReason).String() != "string" { + t.Error("Test Failed - Alphapoint products.RejectReason value is not a string") + } + + if len(products.Products) >= 1 { + if reflect.ValueOf(products.Products[0]).NumField() != 5 { + t.Error("Test Failed - Alphapoint Getproducts.Products[] struct updated/changed") + } + if reflect.TypeOf(products.Products[0].DecimalPlaces).String() != "int" { + t.Error("Test Failed - Alphapoint products.Products.DecimalPlaces value is not a int") + } + if reflect.TypeOf(products.Products[0].FullName).String() != "string" { + t.Error("Test Failed - Alphapoint products.Products.FullName value is not a string") + } + if reflect.TypeOf(products.Products[0].IsDigital).String() != "bool" { + t.Error("Test Failed - Alphapoint products.Products.IsDigital value is not a bool") + } + if reflect.TypeOf(products.Products[0].Name).String() != "string" { + t.Error("Test Failed - Alphapoint products.Products.Name value is not a string") + } + if reflect.TypeOf(products.Products[0].ProductCode).String() != "int" { + t.Error("Test Failed - Alphapoint products.Products.ProductCode value is not a int") + } + + if products.Products[0].DecimalPlaces < 0 { + t.Error("Test Failed - Alphapoint products.Products.DecimalPlaces value is negative") + } + if products.Products[0].ProductCode < 0 { + t.Log(products.Products[0].ProductCode) + t.Error("Test Failed - Alphapoint products.Products.ProductCode value is negative") + } + } else { + t.Error("Test Failed - Alphapoint products.Products no product pairs.") + } +} + +func TestCreateAccount(t *testing.T) { + CreateAccount := Alphapoint{} + CreateAccount.SetDefaults() + + err := CreateAccount.CreateAccount("test", "account", "oharareid.ryan@gmail.com", "0433588258", "lolcat123") + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } +} + +func TestGetUserInfo(t *testing.T) { + GetUserInfo := Alphapoint{} + GetUserInfo.SetDefaults() + + userInfo, err := GetUserInfo.GetUserInfo() + if err != nil { + t.Errorf("Test Failed - Init error: %s", err) + } + t.Log(userInfo) +} diff --git a/smsglobal/smsglobal.go b/smsglobal/smsglobal.go index 8084d21e..74c2d822 100644 --- a/smsglobal/smsglobal.go +++ b/smsglobal/smsglobal.go @@ -26,7 +26,7 @@ func GetEnabledSMSContacts(smsCfg config.SMSGlobalConfig) int { return counter } -func SMSSendToAll(message string, cfg config.Config) { +func SMSSendToAll(message string, cfg config.Config) { // return error here for _, contact := range cfg.SMS.Contacts { if contact.Enabled { err := SMSNotify(contact.Number, message, cfg) diff --git a/smsglobal/smsglobal_tests/smsglobal_test.go b/smsglobal/smsglobal_test.go similarity index 68% rename from smsglobal/smsglobal_tests/smsglobal_test.go rename to smsglobal/smsglobal_test.go index abd14cd1..dbbdcc18 100644 --- a/smsglobal/smsglobal_tests/smsglobal_test.go +++ b/smsglobal/smsglobal_test.go @@ -1,20 +1,19 @@ -package test +package smsglobal import ( "testing" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/smsglobal" ) func TestGetEnabledSMSContacts(t *testing.T) { cfg := config.GetConfig() - err := cfg.LoadConfig() + err := cfg.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test Failed. GetEnabledSMSContacts: \nFunction return is incorrect with, %s.", err) } - numberOfContacts := smsglobal.GetEnabledSMSContacts(cfg.SMS) + numberOfContacts := GetEnabledSMSContacts(cfg.SMS) if numberOfContacts != len(cfg.SMS.Contacts) { t.Errorf("Test Failed. GetEnabledSMSContacts: \nFunction return is incorrect with, %d.", numberOfContacts) } @@ -22,21 +21,21 @@ func TestGetEnabledSMSContacts(t *testing.T) { func TestSMSSendToAll(t *testing.T) { cfg := config.GetConfig() - err := cfg.LoadConfig() + err := cfg.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test Failed. SMSSendToAll: \nFunction return is incorrect with, %s.", err) } - smsglobal.SMSSendToAll("Test", *cfg) //+60sec reply issue without account details + SMSSendToAll("SMSGLOBAL Test - SMSSENDTOALL", *cfg) //+60sec reply issue without account details } func TestSMSGetNumberByName(t *testing.T) { cfg := config.GetConfig() - err := cfg.LoadConfig() + err := cfg.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test Failed. SMSGetNumberByName: \nFunction return is incorrect with, %s.", err) } - number := smsglobal.SMSGetNumberByName("POLYESTERGIRL", cfg.SMS) + number := SMSGetNumberByName("StyleGherkin", cfg.SMS) if number == "" { t.Error("Test Failed. SMSNotify: \nError: No number, name not found.") } @@ -44,12 +43,12 @@ func TestSMSGetNumberByName(t *testing.T) { func TestSMSNotify(t *testing.T) { cfg := config.GetConfig() - err := cfg.LoadConfig() + err := cfg.LoadConfig("../testdata/configtest.dat") if err != nil { t.Errorf("Test Failed. SMSNotify: \nFunction return is incorrect with, %s.", err) } - err2 := smsglobal.SMSNotify(cfg.SMS.Contacts[0].Number, "Test", *cfg) + err2 := SMSNotify(cfg.SMS.Contacts[0].Number, "SMSGLOBAL Test - SMS SEND TO SINGLE", *cfg) if err2 != nil { t.Error("Test Failed. SMSNotify: \nError: ", err2) } diff --git a/smsglobal/smsglobal_tests/config_example.dat b/testdata/configtest.dat similarity index 95% rename from smsglobal/smsglobal_tests/config_example.dat rename to testdata/configtest.dat index 973ffa04..10d9ed16 100644 --- a/smsglobal/smsglobal_tests/config_example.dat +++ b/testdata/configtest.dat @@ -17,24 +17,24 @@ { "Address": "LgY8ahfHRhvjVQC1zJnBhFMG5pCTMuKRqh", "CoinType": "LTC", - "Balance": 3.00000005e+06 + "Balance": 3000000.05 }, { "Address": "0xb794f5ea0ba39494ce839613fffba74279579268", "CoinType": "ETH", - "Balance": 5.774999820458524e+06 + "Balance": 5774999.820458524 } ] }, "SMSGlobal": { - "Enabled": false, - "Username": "Username", - "Password": "Password", + "Enabled": true, + "Username": "1234", + "Password": "12334", "Contacts": [ { - "Name": "Bob", - "Number": "12345", - "Enabled": false + "Name": "StyleGherkin", + "Number": "1231424", + "Enabled": true } ] }, @@ -54,7 +54,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", "EnabledPairs": "BTCUSD,BTCHKD,BTCEUR,BTCCAD,BTCAUD,BTCSGD,BTCJPY,BTCGBP,BTCNZD,LTCBTC,DOGEBTC,STRBTC,XRPBTC", "BaseCurrencies": "USD,HKD,EUR,CAD,AUD,SGD,JPY,GBP,NZD" @@ -68,7 +67,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC,ETCBTC,ETCUSD,BFXUSD,BFXBTC,RRTUSD,RRTBTC,ZECUSD,ZECBTC,XMRUSD,XMRBTC,DSHUSD,DSHBTC", "EnabledPairs": "BTCUSD,LTCUSD,LTCBTC,ETHUSD,ETHBTC", "BaseCurrencies": "USD" @@ -96,7 +94,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCCNY,LTCCNY,LTCBTC", "EnabledPairs": "BTCCNY,LTCCNY,LTCBTC", "BaseCurrencies": "CNY" @@ -110,7 +107,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", "EnabledPairs": "BTCUSD,BTCRUR,BTCEUR,LTCBTC,LTCUSD,LTCRUR,LTCEUR,NMCBTC,NMCUSD,NVCBTC,NVCUSD,USDRUR,EURUSD,EURRUR,PPCBTC,PPCUSD", "BaseCurrencies": "USD,RUR,EUR" @@ -124,7 +120,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "LTC,BTC", "EnabledPairs": "LTC,BTC", "BaseCurrencies": "AUD" @@ -152,7 +147,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCUSD,ETHBTC,ETHUSD", "EnabledPairs": "BTCUSD", "BaseCurrencies": "USD" @@ -166,7 +160,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCCNY,LTCCNY", "EnabledPairs": "BTCCNY,LTCCNY", "BaseCurrencies": "CNY" @@ -194,7 +187,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "ETCUSD,ICNETH,REPXBT,ZECXBT,ETHXBT,ETHXBT.d,ETHGBP,LTCXBT,XBTGBP.d,XDGXBT,XMRUSD,ZECUSD,ETCETH,ETHJPY,XBTCAD.d,XBTJPY.d,XBTUSD.d,XLMXBT,XLMEUR,XLMUSD,XMREUR,ETCXBT,ETHCAD.d,ETHEUR.d,ETHJPY.d,XBTEUR.d,ETHEUR,ETHGBP.d,ICNXBT,LTCEUR,REPEUR,XBTGBP,XBTJPY,ETHUSD,ETHUSD.d,LTCUSD,REPETH,XBTUSD,XMRXBT,ETCEUR,ETHCAD,REPUSD,XBTCAD,XBTEUR,XRPXBT,ZECEUR", "EnabledPairs": "ETCUSD,XBTUSD,ETHUSD", "BaseCurrencies": "EUR,USD,CAD,GBP,JPY" @@ -208,7 +200,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCUSD,BTCEUR,USDHKD,AUDUSD,BTCGBP,BTCNZD,USDJPY,BTCSGD,BTCNGN,EURUSD,USDSGD,NZDUSD,USDNGN,USDCHF,BTCJPY,BTCAUD,BTCCAD,BTCCHF,GBPUSD,USDCAD", "EnabledPairs": "BTCUSD,BTCAUD", "BaseCurrencies": "USD,EUR,HKD,AUD,GBP,NZD,JPY,SGD,NGN,CHF,CAD" @@ -222,7 +213,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "TIME_BTC,ETH_BTC,GNT_BTC,WAVES_BTC,ICN_BTC,1ST_BTC,WINGS_BTC,MLN_BTC,ROUND_BTC,VSL_BTC,LTC_BTC,DCT_BTC,INCNT_BTC,PLU_BTC,DASH_BTC", "EnabledPairs": "ETH_BTC,LTC_BTC,DASH_BTC", "BaseCurrencies": "USD" @@ -236,7 +226,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", "EnabledPairs": "BTCARS,BTCAUD,BTCBRL,BTCCAD,BTCCHF,BTCCZK,BTCDKK,BTCEUR,BTCGBP,BTCHKD,BTCILS,BTCINR,BTCMXN,BTCNOK,BTCNZD,BTCPLN,BTCRUB,BTCSEK,BTCSGD,BTCTHB,BTCUSD,BTCZAR", "BaseCurrencies": "ARS,AUD,BRL,CAD,CHF,CZK,DKK,EUR,GBP,HKD,ILS,INR,MXN,NOK,NZD,PLN,RUB,SEK,SGD,THB,USD,ZAR" @@ -250,7 +239,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCCNY,LTCCNY", "EnabledPairs": "BTCCNY,LTCCNY", "BaseCurrencies": "CNY" @@ -264,7 +252,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTCUSD,LTCUSD", "EnabledPairs": "BTCUSD,LTCUSD", "BaseCurrencies": "USD" @@ -278,7 +265,6 @@ "AuthenticatedAPISupport": false, "APIKey": "Key", "APISecret": "Secret", - "ClientID": "", "AvailablePairs": "BTC_XUSD,BTC_FCT,BTC_MMNXT,BTC_NMC,BTC_BITUSD,BTC_RDD,BTC_XMR,BTC_XST,BTC_DSH,BTC_MAID,BTC_DGB,BTC_NEOS,BTC_BLK,BTC_NAUT,BTC_NBT,BTC_XCP,BTC_STR,BTC_BTCD,BTC_GRC,BTC_HUC,BTC_BBR,BTC_XDN,BTC_INDEX,BTC_IOC,BTC_SWARM,BTC_EMC2,BTC_MCN,BTC_NOXT,BTC_MINT,BTC_PTS,BTC_SC,BTC_GEO,BTC_XRP,BTC_FLO,BTC_BITS,BTC_HYP,BTC_XCR,BTC_LTBC,BTC_SYS,BTC_GMC,BTC_ETH,BTC_SYNC,BTC_GAP,BTC_BCN,BTC_C2,BTC_PINK,BTC_FIBRE,BTC_POT,BTC_QTL,BTC_SDC,BTC_XC,BTC_DASH,BTC_SILK,BTC_CLAM,BTC_NAV,BTC_PIGGY,BTC_BCY,BTC_MIL,BTC_XCN,BTC_YACC,BTC_BTS,BTC_QBK,BTC_SJCX,BTC_LQD,BTC_BURST,BTC_RIC,BTC_VRC,BTC_LTC,BTC_XPB,BTC_GRS,BTC_XCH,BTC_ARCH,BTC_QORA,BTC_HZ,BTC_NSR,BTC_XPM,BTC_BITCNY,BTC_EXE,BTC_XMG,BTC_BTC,BTC_BTM,BTC_NOBL,BTC_NXT,BTC_DOGE,BTC_CURE,BTC_MNTA,BTC_ADN,BTC_EXP,BTC_VTC,BTC_FLDC,BTC_MRS,BTC_MYR,BTC_OMNI,BTC_VNL,BTC_USDT,BTC_NOTE,BTC_WDC,BTC_BELA,BTC_VIA,BTC_CGA,BTC_DIEM,BTC_IFC,BTC_XDP,BTC_BLOCK,BTC_MMC,BTC_1CR,BTC_UNITY,BTC_XBC,BTC_GEMZ,BTC_FLT,BTC_PPC,BTC_XEM,BTC_RBY,BTC_CNMT,BTC_ABY,XMR_XDN,XMR_IFC,XMR_DIEM,XMR_BBR,XMR_DSH,XMR_BCN,XMR_LTC,XMR_MAID,XMR_DASH,XMR_BTCD,XMR_HYP,XMR_BLK,XMR_QORA,XMR_MNTA,XMR_NXT,USDT_BTC,USDT_ETH,USDT_XRP,USDT_DASH,USDT_LTC,USDT_NXT,USDT_XMR,USDT_STR", "EnabledPairs": "BTC_LTC,BTC_ETH,BTC_DOGE,BTC_DASH,BTC_XRP", "BaseCurrencies": "USD" From 68cf098e9c66e28dc1c9ae0a43a4169dba194f07 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 10 Apr 2017 14:18:48 +1000 Subject: [PATCH 19/37] Add Exchange Tests --- exchanges/exchange_test.go | 86 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 exchanges/exchange_test.go diff --git a/exchanges/exchange_test.go b/exchanges/exchange_test.go new file mode 100644 index 00000000..119f5a9c --- /dev/null +++ b/exchanges/exchange_test.go @@ -0,0 +1,86 @@ +package exchange + +import ( + "testing" + + "github.com/thrasher-/gocryptotrader/config" +) + +func TestGetName(t *testing.T) { + GetName := ExchangeBase{ + Name: "TESTNAME", + } + + name := GetName.GetName() + if name != "TESTNAME" { + t.Error("Test Failed - Exchange getName() returned incorrect name") + } +} + +func TestGetEnabledCurrencies(t *testing.T) { + enabledPairs := []string{"BTCUSD", "BTCAUD", "LTCUSD", "LTCAUD"} + GetEnabledCurrencies := ExchangeBase{ + Name: "TESTNAME", + EnabledPairs: enabledPairs, + } + + enCurr := GetEnabledCurrencies.GetEnabledCurrencies() + if enCurr[0] != "BTCUSD" { + t.Error("Test Failed - Exchange GetEnabledCurrencies() incorrect string") + } +} + +func TestSetEnabled(t *testing.T) { + GetEnabledCurrencies := ExchangeBase{ + Name: "TESTNAME", + Enabled: false, + } + + GetEnabledCurrencies.SetEnabled(true) + if !GetEnabledCurrencies.Enabled { + t.Error("Test Failed - Exchange SetEnabled(true) did not set boolean") + } +} + +func TestIsEnabled(t *testing.T) { + GetEnabledCurrencies := ExchangeBase{ + Name: "TESTNAME", + Enabled: false, + } + + if GetEnabledCurrencies.IsEnabled() { + t.Error("Test Failed - Exchange IsEnabled() did not return correct boolean") + } +} + +func TestSetAPIKeys(t *testing.T) { + SetAPIKeys := ExchangeBase{ + Name: "TESTNAME", + Enabled: false, + } + + SetAPIKeys.SetAPIKeys("RocketMan", "Digereedoo", "007", false) + + if SetAPIKeys.APIKey != "RocketMan" && SetAPIKeys.APISecret != "Digereedoo" && SetAPIKeys.ClientID != "007" { + t.Error("Test Failed - Exchange SetAPIKeys() did not set correct values") + } + +} + +func TestUpdateAvailableCurrencies(t *testing.T) { + cfg := config.GetConfig() + err := cfg.LoadConfig("../testdata/configtest.dat") + if err != nil { + t.Log("SOMETHING DONE HAPPENED!") + } + + UAC := ExchangeBase{ + Name: "ANX", + } + exchangeProducts := []string{"ltc", "btc", "usd", "aud"} + + err2 := UAC.UpdateAvailableCurrencies(exchangeProducts) + if err2 != nil { + t.Errorf("Test Failed - Exchange UpdateAvailableCurrencies() error: %s", err2) + } +} From a2c0e52f937c594dfd9901bec387fee65abdbc7b Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 10 Apr 2017 15:20:26 +1000 Subject: [PATCH 20/37] Changed incorrect names --- exchanges/exchange_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/exchanges/exchange_test.go b/exchanges/exchange_test.go index 119f5a9c..9b8a2ff4 100644 --- a/exchanges/exchange_test.go +++ b/exchanges/exchange_test.go @@ -31,24 +31,24 @@ func TestGetEnabledCurrencies(t *testing.T) { } func TestSetEnabled(t *testing.T) { - GetEnabledCurrencies := ExchangeBase{ + SetEnabled := ExchangeBase{ Name: "TESTNAME", Enabled: false, } - GetEnabledCurrencies.SetEnabled(true) - if !GetEnabledCurrencies.Enabled { + SetEnabled.SetEnabled(true) + if !SetEnabled.Enabled { t.Error("Test Failed - Exchange SetEnabled(true) did not set boolean") } } func TestIsEnabled(t *testing.T) { - GetEnabledCurrencies := ExchangeBase{ + IsEnabled := ExchangeBase{ Name: "TESTNAME", Enabled: false, } - if GetEnabledCurrencies.IsEnabled() { + if IsEnabled.IsEnabled() { t.Error("Test Failed - Exchange IsEnabled() did not return correct boolean") } } From 9a6484e113ab6975046c19c27b1fc22ac80b7e54 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 11 Apr 2017 14:39:31 +1000 Subject: [PATCH 21/37] Added ticker_test.go --- exchanges/ticker/ticker.go | 4 + exchanges/ticker/ticker_test.go | 239 ++++++++++++++++++++++++++++++++ 2 files changed, 243 insertions(+) create mode 100644 exchanges/ticker/ticker_test.go diff --git a/exchanges/ticker/ticker.go b/exchanges/ticker/ticker.go index f2cd99e8..8307af8b 100644 --- a/exchanges/ticker/ticker.go +++ b/exchanges/ticker/ticker.go @@ -3,6 +3,8 @@ package ticker import ( "errors" "strconv" + + "github.com/thrasher-/gocryptotrader/common" ) var ( @@ -32,6 +34,7 @@ type Ticker struct { } func (t *Ticker) PriceToString(firstCurrency, secondCurrency, priceType string) string { + priceType = common.StringToLower(priceType) switch priceType { case "last": return strconv.FormatFloat(t.Price[firstCurrency][secondCurrency].Last, 'f', -1, 64) @@ -117,6 +120,7 @@ func ProcessTicker(exchangeName string, firstCurrency, secondCurrency string, ti if len(Tickers) == 0 { CreateNewTicker(exchangeName, firstCurrency, secondCurrency, tickerNew) + //issue - not appending return } else { ticker, err := GetTickerByExchange(exchangeName) diff --git a/exchanges/ticker/ticker_test.go b/exchanges/ticker/ticker_test.go new file mode 100644 index 00000000..281715a2 --- /dev/null +++ b/exchanges/ticker/ticker_test.go @@ -0,0 +1,239 @@ +package ticker + +import ( + "reflect" + "testing" +) + +func TestPriceToString(t *testing.T) { + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + newTicker := CreateNewTicker("ANX", "BTC", "USD", priceStruct) + + if newTicker.PriceToString("BTC", "USD", "last") != "1200" { + t.Error("Test Failed - ticker PriceToString last value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "high") != "1298" { + t.Error("Test Failed - ticker PriceToString high value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "low") != "1148" { + t.Error("Test Failed - ticker PriceToString low value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "bid") != "1195" { + t.Error("Test Failed - ticker PriceToString bid value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "ask") != "1220" { + t.Error("Test Failed - ticker PriceToString ask value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "volume") != "5" { + t.Error("Test Failed - ticker PriceToString volume value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "ath") != "1337" { + t.Error("Test Failed - ticker PriceToString ath value is incorrect") + } + if newTicker.PriceToString("BTC", "USD", "obtuse") != "" { + t.Error("Test Failed - ticker PriceToString obtuse value is incorrect") + } +} + +func TestGetTicker(t *testing.T) { + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + bitfinexTicker := CreateNewTicker("bitfinex", "BTC", "USD", priceStruct) + Tickers = append(Tickers, bitfinexTicker) + + tickerPrice, err := GetTicker("bitfinex", "BTC", "USD") + if err != nil { + t.Errorf("Test Failed - Ticker GetTicker init error: %s", err) + } + if tickerPrice.CurrencyPair != "BTCUSD" { + t.Error("Test Failed - ticker tickerPrice.CurrencyPair value is incorrect") + } +} + +func TestGetTickerByExchange(t *testing.T) { + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + anxTicker := CreateNewTicker("ANX", "BTC", "USD", priceStruct) + Tickers = append(Tickers, anxTicker) + + tickerPtr, err := GetTickerByExchange("ANX") + 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 TestFirstCurrencyExists(t *testing.T) { + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + alphaTicker := CreateNewTicker("alphapoint", "BTC", "USD", priceStruct) + Tickers = append(Tickers, alphaTicker) + + if !FirstCurrencyExists("alphapoint", "BTC") { + t.Error("Test Failed - FirstCurrencyExists1 value return is incorrect") + } + if FirstCurrencyExists("alphapoint", "CATS") { + t.Error("Test Failed - FirstCurrencyExists2 value return is incorrect") + } +} + +func TestSecondCurrencyExists(t *testing.T) { + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + bitstampTicker := CreateNewTicker("bitstamp", "BTC", "USD", priceStruct) + Tickers = append(Tickers, bitstampTicker) + + if !SecondCurrencyExists("bitstamp", "BTC", "USD") { + t.Error("Test Failed - SecondCurrencyExists1 value return is incorrect") + } + if SecondCurrencyExists("bitstamp", "BTC", "DOGS") { + t.Error("Test Failed - SecondCurrencyExists2 value return is incorrect") + } +} + +func TestCreateNewTicker(t *testing.T) { + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + newTicker := CreateNewTicker("ANX", "BTC", "USD", priceStruct) + + 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 reflect.TypeOf(newTicker.Price["BTC"]["USD"].Ask).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Ask value is not a float64") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].Bid).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Bid value is not a float64") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].CurrencyPair).String() != "string" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].CurrencyPair value is not a string") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].FirstCurrency).String() != "string" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].FirstCurrency value is not a string") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].High).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].High value is not a float64") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].Last).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Last value is not a float64") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].Low).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Low value is not a float64") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].PriceATH).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].PriceATH value is not a float64") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].SecondCurrency).String() != "string" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].SecondCurrency value is not a string") + } + if reflect.TypeOf(newTicker.Price["BTC"]["USD"].Volume).String() != "float64" { + t.Error("Test Failed - ticker newTicker.Price[BTC][USD].Volume value is not a float64") + } +} + +func TestProcessTicker(t *testing.T) { //non-appending function to tickers + t.Parallel() + + priceStruct := TickerPrice{ + FirstCurrency: "BTC", + SecondCurrency: "USD", + CurrencyPair: "BTCUSD", + Last: 1200, + High: 1298, + Low: 1148, + Bid: 1195, + Ask: 1220, + Volume: 5, + PriceATH: 1337, + } + + ProcessTicker("btcc", "BTC", "USD", priceStruct) +} From 8e9d6095c4c1c7a9ca80627c6be855e8473bd83e Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 11 Apr 2017 17:37:26 +1000 Subject: [PATCH 22/37] Added tests for stats.go --- exchanges/stats/stats_test.go | 139 ++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 exchanges/stats/stats_test.go diff --git a/exchanges/stats/stats_test.go b/exchanges/stats/stats_test.go new file mode 100644 index 00000000..812823ef --- /dev/null +++ b/exchanges/stats/stats_test.go @@ -0,0 +1,139 @@ +package stats + +import ( + "testing" +) + +func TestLenByPrice(t *testing.T) { + exchangeInfo := ExchangeInfo{ + Exchange: "ANX", + FirstCurrency: "BTC", + FiatCurrency: "USD", + Price: 1200, + Volume: 5, + } + + ExchInfo = append(ExchInfo, exchangeInfo) + if ByPrice.Len(ExchInfo) < 1 { + t.Error("Test Failed - stats LenByPrice() length not correct.") + } +} + +func TestLessByPrice(t *testing.T) { + exchangeInfo := ExchangeInfo{ + Exchange: "alphapoint", + FirstCurrency: "BTC", + FiatCurrency: "USD", + Price: 1200, + Volume: 5, + } + + exchangeInfo2 := ExchangeInfo{ + Exchange: "bitfinex", + FirstCurrency: "BTC", + FiatCurrency: "USD", + Price: 1198, + Volume: 20, + } + + ExchInfo = append(ExchInfo, exchangeInfo) + ExchInfo = append(ExchInfo, exchangeInfo2) + + if !ByPrice.Less(ExchInfo, 2, 1) { + t.Error("Test Failed - stats LessByPrice() incorrect return.") + } + if ByPrice.Less(ExchInfo, 1, 2) { + t.Error("Test Failed - stats LessByPrice() incorrect return.") + } +} + +func TestSwapByPrice(t *testing.T) { + exchangeInfo := ExchangeInfo{ + Exchange: "bitstamp", + FirstCurrency: "BTC", + FiatCurrency: "USD", + Price: 1324, + Volume: 5, + } + + exchangeInfo2 := ExchangeInfo{ + Exchange: "btcc", + FirstCurrency: "BTC", + FiatCurrency: "USD", + Price: 7863, + Volume: 20, + } + + ExchInfo = append(ExchInfo, exchangeInfo) + ExchInfo = append(ExchInfo, exchangeInfo2) + ByPrice.Swap(ExchInfo, 3, 4) + if ExchInfo[3].Exchange != "btcc" || ExchInfo[4].Exchange != "bitstamp" { + t.Error("Test Failed - stats SwapByPrice did not swap values.") + } +} + +func TestLenByVolume(t *testing.T) { + if ByVolume.Len(ExchInfo) != 5 { + t.Error("Test Failed - stats lenByVolume did not swap values.") + } +} + +func TestLessByVolume(t *testing.T) { + if !ByVolume.Less(ExchInfo, 1, 2) { + t.Error("Test Failed - stats LessByVolume() incorrect return.") + } + if ByVolume.Less(ExchInfo, 2, 1) { + t.Error("Test Failed - stats LessByVolume() incorrect return.") + } +} + +func TestSwapByVolume(t *testing.T) { + ByPrice.Swap(ExchInfo, 3, 4) + + if ExchInfo[4].Exchange != "btcc" || ExchInfo[3].Exchange != "bitstamp" { + t.Error("Test Failed - stats SwapByVolume did not swap values.") + } +} + +func TestAddExchangeInfo(t *testing.T) { + ExchInfo = ExchInfo[:0] + AddExchangeInfo("ANX", "BTC", "USD", 1200, 42) + + if len(ExchInfo) < 1 { + t.Error("Test Failed - stats AddExchangeInfo did not add exchange info.") + } +} + +func TestAppendExchangeInfo(t *testing.T) { + AppendExchangeInfo("sillyexchange", "BTC", "USD", 1234, 45) + if len(ExchInfo) < 2 { + t.Error("Test Failed - stats AppendExchangeInfo did not add exchange values.") + } + AppendExchangeInfo("sillyexchange", "BTC", "USD", 1234, 45) + if len(ExchInfo) == 3 { + t.Error("Test Failed - stats AppendExchangeInfo added exchange values") + } +} + +func TestExchangeInfoAlreadyExists(t *testing.T) { + if !ExchangeInfoAlreadyExists("ANX", "BTC", "USD", 1200, 42) { + t.Error("Test Failed - stats ExchangeInfoAlreadyExists exchange does not exist.") + } + if ExchangeInfoAlreadyExists("bla", "dii", "USD", 1234, 123) { + t.Error("Test Failed - stats ExchangeInfoAlreadyExists found incorrect exchange.") + } +} + +func TestSortExchangesByVolume(t *testing.T) { + topVolume := SortExchangesByVolume("BTC", "USD", true) + if topVolume[0].Exchange != "sillyexchange" { + t.Error("Test Failed - stats SortExchangesByVolume incorrectly sorted values.") + } +} + +func TestSortExchangesByPrice(t *testing.T) { + topPrice := SortExchangesByPrice("BTC", "USD", true) + if topPrice[0].Exchange != "sillyexchange" { + t.Error("Test Failed - stats SortExchangesByPrice incorrectly sorted values.") + } +} From c425d7dba44689edc1b5b8fcc5119b7c6e46bb12 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 11 Apr 2017 22:25:01 +1000 Subject: [PATCH 23/37] Moved checking function downstream + Added default currency for test --- exchanges/stats/stats.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/exchanges/stats/stats.go b/exchanges/stats/stats.go index 39eb6292..40dc7183 100644 --- a/exchanges/stats/stats.go +++ b/exchanges/stats/stats.go @@ -45,21 +45,22 @@ func (this ByVolume) Swap(i, j int) { } func AddExchangeInfo(exchange, crypto, fiat string, price, volume float64) { + if currency.BaseCurrencies == "" { + currency.BaseCurrencies = currency.DEFAULT_CURRENCIES + } + if !currency.IsFiatCurrency(fiat) { return } - if len(ExchInfo) == 0 { - AppendExchangeInfo(exchange, crypto, fiat, price, volume) - } else { - if ExchangeInfoAlreadyExists(exchange, crypto, fiat, price, volume) { - return - } else { - AppendExchangeInfo(exchange, crypto, fiat, price, volume) - } - } + AppendExchangeInfo(exchange, crypto, fiat, price, volume) + } func AppendExchangeInfo(exchange, crypto, fiat string, price, volume float64) { + if ExchangeInfoAlreadyExists(exchange, crypto, fiat, price, volume) { + return + } + exch := ExchangeInfo{} exch.Exchange = exchange exch.FirstCurrency = crypto From 6daba21982126396f4c2391421151827f5e9275e Mon Sep 17 00:00:00 2001 From: Adrian Gallagher Date: Tue, 11 Apr 2017 22:50:27 +1000 Subject: [PATCH 24/37] Config: Add missing params --- config_routes.go | 4 ++-- main.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/config_routes.go b/config_routes.go index 898a8bfa..416eef25 100644 --- a/config_routes.go +++ b/config_routes.go @@ -35,11 +35,11 @@ func SaveAllSettings(w http.ResponseWriter, r *http.Request) { } } //Reload the configuration - err := bot.config.SaveConfig() + err := bot.config.SaveConfig("") if err != nil { panic(err) } - err = bot.config.LoadConfig() + err = bot.config.LoadConfig("") if err != nil { panic(err) } diff --git a/main.go b/main.go index 93872c9a..9ea40d41 100644 --- a/main.go +++ b/main.go @@ -89,7 +89,7 @@ func main() { bot.config = &config.Cfg log.Printf("Loading config file %s..\n", config.CONFIG_FILE) - err := bot.config.LoadConfig() + err := bot.config.LoadConfig("") if err != nil { log.Fatal(err) } @@ -208,7 +208,7 @@ func HandleInterrupt() { func Shutdown() { log.Println("Bot shutting down..") bot.config.Portfolio = portfolio.Portfolio - err := bot.config.SaveConfig() + err := bot.config.SaveConfig("") if err != nil { log.Println("Unable to save config.") From c6b7e35dd84cf280a27304af4633df974c3333a3 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Wed, 12 Apr 2017 15:34:20 +1000 Subject: [PATCH 25/37] Fixed typo --- exchanges/bitfinex/bitfinex.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exchanges/bitfinex/bitfinex.go b/exchanges/bitfinex/bitfinex.go index 1f770082..5a0916cb 100644 --- a/exchanges/bitfinex/bitfinex.go +++ b/exchanges/bitfinex/bitfinex.go @@ -246,7 +246,7 @@ func (b *Bitfinex) CancelOrder(OrderID int64) (BitfinexOrder, error) { return response, nil } -func (b *Bitfinex) CancelMultiplateOrders(OrderIDs []int64) (string, error) { +func (b *Bitfinex) CancelMultipleOrders(OrderIDs []int64) (string, error) { request := make(map[string]interface{}) request["order_ids"] = OrderIDs response := BitfinexGenericResponse{} From ae5864a715962c298cb56278ba75ede13081d190 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Wed, 12 Apr 2017 15:35:25 +1000 Subject: [PATCH 26/37] Added more test functionality for bitfinex. --- exchanges/bitfinex/bitfinex_test.go | 704 +++++++++++++++++++++++++--- 1 file changed, 647 insertions(+), 57 deletions(-) diff --git a/exchanges/bitfinex/bitfinex_test.go b/exchanges/bitfinex/bitfinex_test.go index 725f8573..bab65e20 100644 --- a/exchanges/bitfinex/bitfinex_test.go +++ b/exchanges/bitfinex/bitfinex_test.go @@ -6,14 +6,59 @@ import ( "reflect" "strconv" "testing" + "time" "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/gocryptotrader/config" + "github.com/thrasher-/gocryptotrader/currency" ) -var ACCOUNT_LIVE_TEST bool = false +var ACCOUNT_LIVE_TEST bool = false //Supply correct API keys in testdata/configtest.dat before changing this. -//Live Testing -- TestBitfinexGetTicker() -func TestBitfinexGetTicker(t *testing.T) { +func TestSetDefaults(t *testing.T) { + t.Parallel() + + setDefaults := Bitfinex{} + setDefaults.SetDefaults() + + if setDefaults.Name != "Bitfinex" || setDefaults.Enabled != false || setDefaults.Verbose != false || + setDefaults.Websocket != false || setDefaults.RESTPollingDelay != 10 { + t.Error("Test Failed - Bitfinex SetDefaults values not set correctly") + } + if reflect.TypeOf(setDefaults.WebsocketSubdChannels).String() != "map[int]bitfinex.BitfinexWebsocketChanInfo" { + t.Error("Test Failed - Bitfinex SetDefaults value: MAP not set correctly") + } +} + +func TestSetup(t *testing.T) { + t.Parallel() + + testConfig := config.ExchangeConfig{ + Enabled: true, + AuthenticatedAPISupport: true, + APIKey: "lamb", + APISecret: "cutlets", + RESTPollingDelay: time.Duration(10), + Verbose: true, + Websocket: true, + BaseCurrencies: currency.DEFAULT_CURRENCIES, + AvailablePairs: currency.MakecurrencyPairs(currency.DEFAULT_CURRENCIES), + EnabledPairs: currency.MakecurrencyPairs(currency.DEFAULT_CURRENCIES), + } + setup := Bitfinex{} + setup.Setup(testConfig) + + if !setup.Enabled || !setup.AuthenticatedAPISupport || setup.APIKey != "lamb" || + setup.APISecret != "cutlets" || setup.RESTPollingDelay != time.Duration(10) || + !setup.Verbose || !setup.Websocket || len(setup.BaseCurrencies) < 1 || + len(setup.AvailablePairs) < 1 || len(setup.EnabledPairs) < 1 { + + t.Error("Test Failed - Bitfinex Setup values not set correctly") + } +} + +//Live Testing +func TestGetTicker(t *testing.T) { t.Parallel() bitfinex := Bitfinex{} @@ -79,8 +124,8 @@ func TestBitfinexGetTicker(t *testing.T) { } } -//Live Testing -- TestBitfinexGetStats() -func TestBitfinexGetStats(t *testing.T) { +//Live Testing +func TestGetStats(t *testing.T) { t.Parallel() BitfinexGetStatsTest := Bitfinex{} @@ -108,8 +153,8 @@ func TestBitfinexGetStats(t *testing.T) { } } -//Live Testing -- TestBitfinexGetLendbook() -func TestBitfinexGetLendbook(t *testing.T) { +//Live Testing +func TestGetLendbook(t *testing.T) { t.Parallel() BitfinexGetLendbook := Bitfinex{} @@ -196,8 +241,8 @@ func TestBitfinexGetLendbook(t *testing.T) { } } -//Live Testing -- TestBitfinexGetOrderbook() -func TestBitfinexGetOrderbook(t *testing.T) { +//Live Testing +func TestGetOrderbook(t *testing.T) { t.Parallel() BitfinexGetOrderbook := Bitfinex{} @@ -282,8 +327,8 @@ func TestBitfinexGetOrderbook(t *testing.T) { } } -//Live Testing -- TestBitfinexGetTrades() -func TestBitfinexGetTrades(t *testing.T) { +//Live Testing +func TestGetTrades(t *testing.T) { t.Parallel() BitfinexGetTrades := Bitfinex{} @@ -343,8 +388,8 @@ func TestBitfinexGetTrades(t *testing.T) { } } -//Live Testing -- TestBitfinexGetLends() -func TestBitfinexGetLends(t *testing.T) { +//Live Testing +func TestGetLends(t *testing.T) { t.Parallel() BitfinexGetLends := Bitfinex{} @@ -384,8 +429,8 @@ func TestBitfinexGetLends(t *testing.T) { } } -//Live Testing -- TestBitfinexGetSymbols() -func TestBitfinexGetSymbols(t *testing.T) { +//Live Testing +func TestGetSymbols(t *testing.T) { t.Parallel() BitfinexGetSymbols := Bitfinex{} @@ -420,26 +465,22 @@ func TestBitfinexGetSymbols(t *testing.T) { "bfxbtc", "rrtusd", } + if len(expectedCurrencies) >= len(symbols) { - if len(expectedCurrencies) == len(symbols) { for _, explicitSymbol := range expectedCurrencies { - for i := 0; i < len(expectedCurrencies); i++ { - if explicitSymbol == symbols[i] { - break - } else if i == (len(expectedCurrencies))-1 { - t.Error("BitfinexGetSymbols currency mismatch with: ", explicitSymbol) - } + if common.DataContains(expectedCurrencies, explicitSymbol) { + break + } else { + t.Error("BitfinexGetSymbols currency mismatch with: ", explicitSymbol) } } - } else if len(expectedCurrencies) > len(symbols) { - t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies > Exchange Currencies") } else { t.Error("BitfinexGetSymbols currency mismatch, Expected Currencies < Exchange Currencies") } } -//Live Testing -- TestBitfinexGetSymbolsDetails() -func TestBitfinexGetSymbolsDetails(t *testing.T) { +//Live Testing +func TestGetSymbolsDetails(t *testing.T) { t.Parallel() BitfinexGetSymbolsDetails := Bitfinex{} @@ -503,10 +544,8 @@ func TestBitfinexGetSymbolsDetails(t *testing.T) { } } -//Hybrid Testing -- TestBitfinexGetAccountInfo() -func TestBitfinexGetAccountInfo(t *testing.T) { - t.Parallel() - +//Hybrid Testing +func TestGetAccountInfo(t *testing.T) { expectedCryptoCurrencies := []string{ "BTC", "LTC", @@ -518,10 +557,23 @@ func TestBitfinexGetAccountInfo(t *testing.T) { } if ACCOUNT_LIVE_TEST { //Live Test + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + BitfinexGetAccountInfo := Bitfinex{} + BitfinexGetAccountInfo.Setup(exchangeConfig) + response, err := BitfinexGetAccountInfo.GetAccountInfo() if err != nil { - newErrString := fmt.Sprintf("TestBitfinexGetAccountInfo: \nError: %s\n", err) + newErrString := fmt.Sprintf("TestGetAccountInfo: \nError: %s\n", err) t.Error(newErrString) response = append(response, BitfinexAccountInfo{}) } @@ -650,9 +702,8 @@ func TestBitfinexGetAccountInfo(t *testing.T) { } } -//Hybrid Testing -- TestBitfinexNewDeposit() -func TestBitfinexNewDeposit(t *testing.T) { //Needs attention - t.Parallel() +//Hybrid Testing +func TestNewDeposit(t *testing.T) { applicableMethods := []string{ "bitcoin_address", @@ -664,24 +715,37 @@ func TestBitfinexNewDeposit(t *testing.T) { //Needs attention "monero_address", } expectedCryptoCurrencies := []string{ - "btc", - "ltc", - "eth", - "etc", - "zec", - "xmr", - "dsh", + "BTC", + "LTC", + "ETH", + "ETC", + "ZEC", + "XMR", + "DSH", } if ACCOUNT_LIVE_TEST { //Live Test + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + BitfinexNewDeposit := Bitfinex{} + BitfinexNewDeposit.Setup(exchangeConfig) + liveResponse, err := BitfinexNewDeposit.NewDeposit("bitcoin", "deposit", 0) if err != nil { t.Error("BitfinexNewDeposit init error: ", err) } if reflect.ValueOf(liveResponse).NumField() != 4 { - t.Error("TestBitfinexNewDeposit struct change/or updated") + t.Error("BitfinexNewDeposit struct change/or updated") } if reflect.TypeOf(liveResponse.Address).String() != "string" { t.Error("Bitfinex NewDeposit.Address is not a string") @@ -695,7 +759,6 @@ func TestBitfinexNewDeposit(t *testing.T) { //Needs attention if reflect.TypeOf(liveResponse.Result).String() != "string" { t.Error("Bitfinex NewDeposit.Result is not a string") } - if len(liveResponse.Address) != 34 { t.Error("Bitfinex NewDeposit.Address is incorrect") } @@ -712,12 +775,12 @@ func TestBitfinexNewDeposit(t *testing.T) { //Needs attention } else { //Non-Live Test nonLiveResponse := BitfinexDepositResponse{} nonLiveResponse.Address = "1DPUgBaZoKbL38BEC1A3exPKCDZjQpnBa1" - nonLiveResponse.Currency = "btc" + nonLiveResponse.Currency = "BTC" nonLiveResponse.Method = "bitcoin_address" nonLiveResponse.Result = "" if reflect.ValueOf(nonLiveResponse).NumField() != 4 { - t.Error("TestBitfinexNewDeposit struct change/or updated") + t.Error("BitfinexNewDeposit struct change/or updated") } if reflect.TypeOf(nonLiveResponse.Address).String() != "string" { t.Error("Bitfinex NewDeposit.Address is not a string") @@ -747,15 +810,26 @@ func TestBitfinexNewDeposit(t *testing.T) { //Needs attention } } -//Non-Live Testing -- TestBitfinexNewOrder() -func TestBitfinexNewOrder(t *testing.T) { - t.Parallel() +//Non-Live Testing +func TestNewOrder(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } BitfinexNewOrder := Bitfinex{} + BitfinexNewOrder.Setup(exchangeConfig) + if ACCOUNT_LIVE_TEST { - response, err := BitfinexNewOrder.NewOrder("BTCUSD", 0.0, 0.0, true, "test", false) - if err != nil { - newErrString := fmt.Sprintf("TestBitfinexNewOrder: \nError: %s\nIs_live: %t\n", err, response.IsLive) + response, err := BitfinexNewOrder.NewOrder("BTCUSD", 0, 0, true, "test", false) + if err == nil { + newErrString := fmt.Sprintf("BitfinexNewOrder - Error: Expected Error Status: %s\n", response.IsLive) t.Error(newErrString) } } @@ -779,7 +853,7 @@ func TestBitfinexNewOrder(t *testing.T) { nonLiveResponse.WasForced = false if reflect.ValueOf(nonLiveResponse).NumField() != 16 { - t.Error("TestBitfinexNewDeposit struct change/or updated") + t.Error("BitfinexNewDeposit struct change/or updated") } if reflect.TypeOf(nonLiveResponse.AverageExecutionPrice).String() != "float64" { t.Error("Bitfinex NewOrder.AverageExecutionPrice is not a float64") @@ -863,11 +937,22 @@ func TestBitfinexNewOrder(t *testing.T) { } } -//Non-Live Testing -- TestBitfinexNewOrderMulti() -func TestBitfinexNewOrderMulti(t *testing.T) { - t.Parallel() +//Non-Live Testing +func TestNewOrderMulti(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } BitfinexNewOrderMulti := Bitfinex{} + BitfinexNewOrderMulti.Setup(exchangeConfig) + var orders []BitfinexPlaceOrder order := BitfinexPlaceOrder{} order.Amount = 0.0 @@ -880,8 +965,8 @@ func TestBitfinexNewOrderMulti(t *testing.T) { if ACCOUNT_LIVE_TEST { response, err := BitfinexNewOrderMulti.NewOrderMulti(orders) - if err != nil { - newErrString := fmt.Sprintf("TestBitfinexNewOrderMulti: \nError: %s\n Status: %s\n", err, response.Status) + if err == nil { + newErrString := fmt.Sprintf("BitfinexNewOrderMulti - Error: Expected Error Status: %s\n", response.Status) t.Error(newErrString) } } @@ -967,3 +1052,508 @@ func TestBitfinexNewOrderMulti(t *testing.T) { t.Error("Bitfinex NewOrderMulti.WasForced is not a bool") } } + +func TestCancelOrder(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexCancelOrder := Bitfinex{} + BitfinexCancelOrder.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexCancelOrder.CancelOrder(1337) + if err == nil { + newErrString := fmt.Sprintf("BitfinexNewOrderMulti - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestCancelMultipleOrders(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexMultipleOrders := Bitfinex{} + BitfinexMultipleOrders.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + orders := []int64{1336, 1337} + response, err := BitfinexMultipleOrders.CancelMultipleOrders(orders) + if err != nil || response != "" { + newErrString := fmt.Sprintf("BitfinexNewOrderMulti - Error: Expected Error", err) + t.Error(newErrString) + } + } +} + +func TestCancelAllOrders(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexCancelAllOrders := Bitfinex{} + BitfinexCancelAllOrders.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + response, err := BitfinexCancelAllOrders.CancelAllOrders() + if err != nil || response != "" { + newErrString := fmt.Sprintf("BitfinexCancelAllOrders - Error: Expected Error", err) + t.Error(newErrString) + } + } +} + +func TestReplaceOrder(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexReplaceOrder := Bitfinex{} + BitfinexReplaceOrder.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexReplaceOrder.ReplaceOrder(1337, "BTC", 0, 0, true, "exchange limit", false) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetOrderStatus(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetOrderStatus := Bitfinex{} + BitfinexGetOrderStatus.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetOrderStatus.GetOrderStatus(1337) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetActiveOrders(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetActiveOrders := Bitfinex{} + BitfinexGetActiveOrders.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetActiveOrders.GetActiveOrders() + if err != nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) + t.Error(newErrString) + } + } +} + +func TestGetActivePositions(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetActivePositions := Bitfinex{} + BitfinexGetActivePositions.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetActivePositions.GetActivePositions() + if err != nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) + t.Error(newErrString) + } + } +} + +func TestClaimPosition(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexClaimPosition := Bitfinex{} + BitfinexClaimPosition.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexClaimPosition.ClaimPosition(1337) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetBalanceHistory(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetBalanceHistory := Bitfinex{} + BitfinexGetBalanceHistory.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetBalanceHistory.GetBalanceHistory("BTC", time.Now(), time.Now(), 1, "testWallet") + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetMovementHistory(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetMovementHistory := Bitfinex{} + BitfinexGetMovementHistory.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetMovementHistory.GetMovementHistory("BTC", "BITCOIN", time.Now(), time.Now(), 1) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetTradeHistory(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetTradeHistory := Bitfinex{} + BitfinexGetTradeHistory.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetTradeHistory.GetTradeHistory("BTC", time.Now(), time.Now(), 1, 0) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestNewOffer(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexNewOffer := Bitfinex{} + BitfinexNewOffer.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + response := BitfinexNewOffer.NewOffer("BTC", 1, 2, 2, "buy") + if response != 0 { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetOfferStatus(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetOfferStatus := Bitfinex{} + BitfinexGetOfferStatus.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetOfferStatus.GetOfferStatus(1337) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetActiveOffers(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetActiveOffers := Bitfinex{} + BitfinexGetActiveOffers.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetActiveOffers.GetActiveOffers() + if err != nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) + t.Error(newErrString) + } + } +} +func TestGetActiveMarginFunding(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetActiveMarginFunding := Bitfinex{} + BitfinexGetActiveMarginFunding.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetActiveMarginFunding.GetActiveMarginFunding() + if err != nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) + t.Error(newErrString) + } + } +} + +func TestGetMarginTotalTakenFunds(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetMarginTotalTakenFunds := Bitfinex{} + BitfinexGetMarginTotalTakenFunds.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetMarginTotalTakenFunds.GetMarginTotalTakenFunds() + if err != nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) + t.Error(newErrString) + } + } +} + +func TestCloseMarginFunding(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexCloseMarginFunding := Bitfinex{} + BitfinexCloseMarginFunding.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexCloseMarginFunding.CloseMarginFunding(1337) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} + +func TestGetAccountBalance(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetAccountBalance := Bitfinex{} + BitfinexGetAccountBalance.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetAccountBalance.GetAccountBalance() + if err != nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) + t.Error(newErrString) + } + } +} + +func TestGetMarginInfo(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexGetMarginInfo := Bitfinex{} + BitfinexGetMarginInfo.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexGetMarginInfo.GetMarginInfo() + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} +func TestWalletTransfer(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexWalletTransfer := Bitfinex{} + BitfinexWalletTransfer.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexWalletTransfer.WalletTransfer(100, "BTC", "somewallet", "someotherwallet") + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} +func TestWithdrawal(t *testing.T) { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - New Order init error: %s\n", err) + } + + BitfinexWithdrawal := Bitfinex{} + BitfinexWithdrawal.Setup(exchangeConfig) + + if ACCOUNT_LIVE_TEST { + _, err := BitfinexWithdrawal.Withdrawal("BITCOIN", "somewallet", "123A87612376", 100) + if err == nil { + newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") + t.Error(newErrString) + } + } +} +func TestSendAuthenticatedHTTPRequest(t *testing.T) { + +} From 9c9444054894528f889a72f3e27b4205c10d6b30 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 17 Apr 2017 14:50:19 +1000 Subject: [PATCH 27/37] changed return statement --- exchanges/bitfinex/bitfinex.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/exchanges/bitfinex/bitfinex.go b/exchanges/bitfinex/bitfinex.go index 5a0916cb..22f7dade 100644 --- a/exchanges/bitfinex/bitfinex.go +++ b/exchanges/bitfinex/bitfinex.go @@ -588,7 +588,7 @@ func (b *Bitfinex) Withdrawal(withdrawType, wallet, address string, amount float return response, nil } -func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[string]interface{}, result interface{}) (err error) { +func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[string]interface{}, result interface{}) error { if len(b.APIKey) == 0 { return errors.New("SendAuthenticatedHTTPRequest: Invalid API key") } @@ -604,7 +604,6 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ } PayloadJson, err := common.JSONEncode(request) - if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") } @@ -634,7 +633,6 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ } err = common.JSONDecode([]byte(resp), &result) - if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON Unmarshal response.") } From 2a6bb52ee8ae714bfb2d78616787f3945c5a43cf Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 17 Apr 2017 14:52:06 +1000 Subject: [PATCH 28/37] added test for SendAuthHTTPRequest --- exchanges/bitfinex/bitfinex_test.go | 184 ++++++++++++++-------------- 1 file changed, 95 insertions(+), 89 deletions(-) diff --git a/exchanges/bitfinex/bitfinex_test.go b/exchanges/bitfinex/bitfinex_test.go index bab65e20..d06baa70 100644 --- a/exchanges/bitfinex/bitfinex_test.go +++ b/exchanges/bitfinex/bitfinex_test.go @@ -827,10 +827,9 @@ func TestNewOrder(t *testing.T) { BitfinexNewOrder.Setup(exchangeConfig) if ACCOUNT_LIVE_TEST { - response, err := BitfinexNewOrder.NewOrder("BTCUSD", 0, 0, true, "test", false) - if err == nil { - newErrString := fmt.Sprintf("BitfinexNewOrder - Error: Expected Error Status: %s\n", response.IsLive) - t.Error(newErrString) + response, errLive := BitfinexNewOrder.NewOrder("BTCUSD", 0, 0, true, "test", false) + if errLive == nil { + t.Errorf("Test Failed - BitfinexNewOrder - Error: Expected Error Status: %t", response.IsLive) } } @@ -1058,11 +1057,11 @@ func TestCancelOrder(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CancelOrder init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CancelOrder init error: %s\n", err) } BitfinexCancelOrder := Bitfinex{} @@ -1071,8 +1070,7 @@ func TestCancelOrder(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexCancelOrder.CancelOrder(1337) if err == nil { - newErrString := fmt.Sprintf("BitfinexNewOrderMulti - Error: Expected Error") - t.Error(newErrString) + t.Errorf("Test Failed - Bitfinex CancelOrder - Error: %s", err) } } } @@ -1082,11 +1080,11 @@ func TestCancelMultipleOrders(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CancelMultipleOrders init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CancelMultipleOrders init error: %s\n", err) } BitfinexMultipleOrders := Bitfinex{} @@ -1096,8 +1094,7 @@ func TestCancelMultipleOrders(t *testing.T) { orders := []int64{1336, 1337} response, err := BitfinexMultipleOrders.CancelMultipleOrders(orders) if err != nil || response != "" { - newErrString := fmt.Sprintf("BitfinexNewOrderMulti - Error: Expected Error", err) - t.Error(newErrString) + t.Errorf("Test Failed - Bitfinex CancelMultipleOrders - Error: %s", err) } } } @@ -1107,11 +1104,11 @@ func TestCancelAllOrders(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CancelAllOrders init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CancelAllOrders init error: %s\n", err) } BitfinexCancelAllOrders := Bitfinex{} @@ -1120,8 +1117,7 @@ func TestCancelAllOrders(t *testing.T) { if ACCOUNT_LIVE_TEST { response, err := BitfinexCancelAllOrders.CancelAllOrders() if err != nil || response != "" { - newErrString := fmt.Sprintf("BitfinexCancelAllOrders - Error: Expected Error", err) - t.Error(newErrString) + t.Errorf("Test Failed - Bitfinex CancelAllOrders - Error: %s", err) } } } @@ -1131,11 +1127,11 @@ func TestReplaceOrder(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex ReplaceOrder init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex ReplaceOrder init error: %s\n", err) } BitfinexReplaceOrder := Bitfinex{} @@ -1144,8 +1140,7 @@ func TestReplaceOrder(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexReplaceOrder.ReplaceOrder(1337, "BTC", 0, 0, true, "exchange limit", false) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex ReplaceOrder - Expected Error") } } } @@ -1155,11 +1150,11 @@ func TestGetOrderStatus(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetOrderStatus init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetOrderStatus init error: %s\n", err) } BitfinexGetOrderStatus := Bitfinex{} @@ -1168,8 +1163,7 @@ func TestGetOrderStatus(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetOrderStatus.GetOrderStatus(1337) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetOrderStatus - Expected Error") } } } @@ -1179,11 +1173,11 @@ func TestGetActiveOrders(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActiveOrders init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActiveOrders init error: %s\n", err) } BitfinexGetActiveOrders := Bitfinex{} @@ -1192,8 +1186,7 @@ func TestGetActiveOrders(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetActiveOrders.GetActiveOrders() if err != nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetActiveOrders - Expected Error") } } } @@ -1203,11 +1196,11 @@ func TestGetActivePositions(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActivePositions init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActivePositions init error: %s\n", err) } BitfinexGetActivePositions := Bitfinex{} @@ -1216,8 +1209,7 @@ func TestGetActivePositions(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetActivePositions.GetActivePositions() if err != nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetActivePositions - Expected Error") } } } @@ -1227,11 +1219,11 @@ func TestClaimPosition(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex ClaimPosition init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex ClaimPosition init error: %s\n", err) } BitfinexClaimPosition := Bitfinex{} @@ -1240,8 +1232,7 @@ func TestClaimPosition(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexClaimPosition.ClaimPosition(1337) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex ClaimPosition - Expected Error") } } } @@ -1251,11 +1242,11 @@ func TestGetBalanceHistory(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetBalanceHistory init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetBalanceHistory init error: %s\n", err) } BitfinexGetBalanceHistory := Bitfinex{} @@ -1264,8 +1255,7 @@ func TestGetBalanceHistory(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetBalanceHistory.GetBalanceHistory("BTC", time.Now(), time.Now(), 1, "testWallet") if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetBalanceHistory - Expected Error") } } } @@ -1275,11 +1265,11 @@ func TestGetMovementHistory(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetMovementHistory init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetMovementHistory init error: %s\n", err) } BitfinexGetMovementHistory := Bitfinex{} @@ -1288,8 +1278,7 @@ func TestGetMovementHistory(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetMovementHistory.GetMovementHistory("BTC", "BITCOIN", time.Now(), time.Now(), 1) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetMovementHistory - Expected Error") } } } @@ -1299,11 +1288,11 @@ func TestGetTradeHistory(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetTradeHistory init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetTradeHistory init error: %s\n", err) } BitfinexGetTradeHistory := Bitfinex{} @@ -1312,8 +1301,7 @@ func TestGetTradeHistory(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetTradeHistory.GetTradeHistory("BTC", time.Now(), time.Now(), 1, 0) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetTradeHistory - Expected Error") } } } @@ -1323,11 +1311,11 @@ func TestNewOffer(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex NewOffer init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex NewOffer init error: %s\n", err) } BitfinexNewOffer := Bitfinex{} @@ -1336,8 +1324,7 @@ func TestNewOffer(t *testing.T) { if ACCOUNT_LIVE_TEST { response := BitfinexNewOffer.NewOffer("BTC", 1, 2, 2, "buy") if response != 0 { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex NewOffer - Expected Error") } } } @@ -1347,11 +1334,11 @@ func TestGetOfferStatus(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetOfferStatus init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetOfferStatus init error: %s\n", err) } BitfinexGetOfferStatus := Bitfinex{} @@ -1360,8 +1347,7 @@ func TestGetOfferStatus(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetOfferStatus.GetOfferStatus(1337) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetOfferStatus - Expected Error") } } } @@ -1371,11 +1357,11 @@ func TestGetActiveOffers(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActiveOffers init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActiveOffers init error: %s\n", err) } BitfinexGetActiveOffers := Bitfinex{} @@ -1384,21 +1370,21 @@ func TestGetActiveOffers(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetActiveOffers.GetActiveOffers() if err != nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetActiveOffers - Expected Error") } } } + func TestGetActiveMarginFunding(t *testing.T) { newConfig := config.Config{} err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActiveMarginFunding init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetActiveMarginFunding init error: %s\n", err) } BitfinexGetActiveMarginFunding := Bitfinex{} @@ -1407,8 +1393,7 @@ func TestGetActiveMarginFunding(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetActiveMarginFunding.GetActiveMarginFunding() if err != nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetActiveMarginFunding - Expected Error") } } } @@ -1418,11 +1403,11 @@ func TestGetMarginTotalTakenFunds(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetMarginTotalTakenFunds init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetMarginTotalTakenFunds init error: %s\n", err) } BitfinexGetMarginTotalTakenFunds := Bitfinex{} @@ -1431,8 +1416,7 @@ func TestGetMarginTotalTakenFunds(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetMarginTotalTakenFunds.GetMarginTotalTakenFunds() if err != nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetMarginTotalTakenFunds - Expected Error") } } } @@ -1442,11 +1426,11 @@ func TestCloseMarginFunding(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CloseMarginFunding init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex CloseMarginFunding init error: %s\n", err) } BitfinexCloseMarginFunding := Bitfinex{} @@ -1455,8 +1439,7 @@ func TestCloseMarginFunding(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexCloseMarginFunding.CloseMarginFunding(1337) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex CloseMarginFunding - Expected Error") } } } @@ -1466,11 +1449,11 @@ func TestGetAccountBalance(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetAccountBalance init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetAccountBalance init error: %s\n", err) } BitfinexGetAccountBalance := Bitfinex{} @@ -1479,8 +1462,7 @@ func TestGetAccountBalance(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetAccountBalance.GetAccountBalance() if err != nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: %s", err) - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetAccountBalance - Expected Error") } } } @@ -1490,11 +1472,11 @@ func TestGetMarginInfo(t *testing.T) { err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetMarginInfo init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex GetMarginInfo init error: %s\n", err) } BitfinexGetMarginInfo := Bitfinex{} @@ -1503,21 +1485,21 @@ func TestGetMarginInfo(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexGetMarginInfo.GetMarginInfo() if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex GetMarginInfo - Expected Error") } } } + func TestWalletTransfer(t *testing.T) { newConfig := config.Config{} err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex WalletTransfer init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex WalletTransfer init error: %s\n", err) } BitfinexWalletTransfer := Bitfinex{} @@ -1526,21 +1508,21 @@ func TestWalletTransfer(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexWalletTransfer.WalletTransfer(100, "BTC", "somewallet", "someotherwallet") if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex WalletTransfer - Expected Error") } } } + func TestWithdrawal(t *testing.T) { newConfig := config.Config{} err := newConfig.LoadConfig("../../testdata/configtest.dat") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex Withdrawal init error: %s\n", err) } exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") if err != nil { - t.Errorf("Test Failed - New Order init error: %s\n", err) + t.Errorf("Test Failed - Bitfinex Withdrawal init error: %s\n", err) } BitfinexWithdrawal := Bitfinex{} @@ -1549,11 +1531,35 @@ func TestWithdrawal(t *testing.T) { if ACCOUNT_LIVE_TEST { _, err := BitfinexWithdrawal.Withdrawal("BITCOIN", "somewallet", "123A87612376", 100) if err == nil { - newErrString := fmt.Sprintf("BitfinexReplaceOrder - Error: Expected Error") - t.Error(newErrString) + t.Error("Test Failed - Bitfinex Withdrawal - Expected Error") } } } -func TestSendAuthenticatedHTTPRequest(t *testing.T) { +func TestSendAuthenticatedHTTPRequest(t *testing.T) { + if ACCOUNT_LIVE_TEST { + newConfig := config.Config{} + + err := newConfig.LoadConfig("../../testdata/configtest.dat") + if err != nil { + t.Errorf("Test Failed - SendAuthenticatedHTTPRequest init error: %s\n", err) + } + exchangeConfig, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - SendAuthenticatedHTTPRequest init error: %s\n", err) + } + + sendAuthHTTPRequest := Bitfinex{} + sendAuthHTTPRequest.Setup(exchangeConfig) + result := []BitfinexAccountInfo{} + + err = sendAuthHTTPRequest.SendAuthenticatedHTTPRequest("POST", BITFINEX_ACCOUNT_INFO, nil, &result) + if err != nil { + t.Errorf("Test Failed - Bitfinex SendAuthenticatedHTTPRequest() error: %s", err) + } + + if len(result) < 1 { + t.Error("Test Failed - Bitfinex SendAuthenticatedHTTPRequest() incorrect length") + } + } } From 413aa9f3b799aa3973f4e876e7e10703a3b41e92 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 17 Apr 2017 14:53:40 +1000 Subject: [PATCH 29/37] changed json string --- exchanges/bitfinex/bitfinex_types.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exchanges/bitfinex/bitfinex_types.go b/exchanges/bitfinex/bitfinex_types.go index 4dbb53be..db9eab38 100644 --- a/exchanges/bitfinex/bitfinex_types.go +++ b/exchanges/bitfinex/bitfinex_types.go @@ -83,7 +83,7 @@ type BitfinexOffer struct { IsCancelled bool `json:"is_cancelled"` OriginalAmount float64 `json:"original_amount,string"` RemainingAmount float64 `json:"remaining_amount,string"` - ExecutedAmount float64 `json:"remaining_amount,string"` + ExecutedAmount float64 `json:"executed_amount,string"` } type BitfinexBookStructure struct { From 0b0df318ea5ae4dc6928ea21ffab73da4aac95b7 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 17 Apr 2017 15:00:35 +1000 Subject: [PATCH 30/37] Added websocket error codes + added return --- exchanges/bitfinex/bitfinex_websocket.go | 41 ++++++++++++++---------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/exchanges/bitfinex/bitfinex_websocket.go b/exchanges/bitfinex/bitfinex_websocket.go index a14fff9e..dc4a86b7 100644 --- a/exchanges/bitfinex/bitfinex_websocket.go +++ b/exchanges/bitfinex/bitfinex_websocket.go @@ -12,20 +12,28 @@ import ( ) const ( - BITFINEX_WEBSOCKET = "wss://api2.bitfinex.com:3000/ws" - BITFINEX_WEBSOCKET_VERSION = "1.1" - BITFINEX_WEBSOCKET_POSITION_SNAPSHOT = "ps" - BITFINEX_WEBSOCKET_POSITION_NEW = "pn" - BITFINEX_WEBSOCKET_POSITION_UPDATE = "pu" - BITFINEX_WEBSOCKET_POSITION_CLOSE = "pc" - BITFINEX_WEBSOCKET_WALLET_SNAPSHOT = "ws" - BITFINEX_WEBSOCKET_WALLET_UPDATE = "wu" - BITFINEX_WEBSOCKET_ORDER_SNAPSHOT = "os" - BITFINEX_WEBSOCKET_ORDER_NEW = "on" - BITFINEX_WEBSOCKET_ORDER_UPDATE = "ou" - BITFINEX_WEBSOCKET_ORDER_CANCEL = "oc" - BITFINEX_WEBSOCKET_TRADE_EXECUTED = "te" - BITFINEX_WEBSOCKET_HEARTBEAT = "hb" + BITFINEX_WEBSOCKET = "wss://api.bitfinex.com/ws" + BITFINEX_WEBSOCKET_VERSION = "1.1" + BITFINEX_WEBSOCKET_POSITION_SNAPSHOT = "ps" + BITFINEX_WEBSOCKET_POSITION_NEW = "pn" + BITFINEX_WEBSOCKET_POSITION_UPDATE = "pu" + BITFINEX_WEBSOCKET_POSITION_CLOSE = "pc" + BITFINEX_WEBSOCKET_WALLET_SNAPSHOT = "ws" + BITFINEX_WEBSOCKET_WALLET_UPDATE = "wu" + BITFINEX_WEBSOCKET_ORDER_SNAPSHOT = "os" + BITFINEX_WEBSOCKET_ORDER_NEW = "on" + BITFINEX_WEBSOCKET_ORDER_UPDATE = "ou" + BITFINEX_WEBSOCKET_ORDER_CANCEL = "oc" + BITFINEX_WEBSOCKET_TRADE_EXECUTED = "te" + BITFINEX_WEBSOCKET_HEARTBEAT = "hb" + BITFINEX_WEBSOCKET_ALERT_RESTARTING = "20051" + BITFINEX_WEBSOCKET_ALERT_REFRESHING = "20060" + BITFINEX_WEBSOCKET_ALERT_RESUME = "20061" + BITFINEX_WEBSOCKET_UNKNOWN_EVENT = "10000" + BITFINEX_WEBSOCKET_UNKNOWN_PAIR = "10001" + BITFINEX_WEBSOCKET_SUBSCRIPTION_FAILED = "10300" + BITFINEX_WEBSOCKET_ALREADY_SUBSCRIBED = "10301" + BITFINEX_WEBSOCKET_UNKNOWN_CHANNEL = "10302" ) func (b *Bitfinex) WebsocketPingHandler() error { @@ -48,7 +56,7 @@ func (b *Bitfinex) WebsocketSend(data interface{}) error { return nil } -func (b *Bitfinex) WebsocketSubscribe(channel string, params map[string]string) { +func (b *Bitfinex) WebsocketSubscribe(channel string, params map[string]string) error { request := make(map[string]string) request["event"] = "subscribe" request["channel"] = channel @@ -58,8 +66,7 @@ func (b *Bitfinex) WebsocketSubscribe(channel string, params map[string]string) request[k] = v } } - - b.WebsocketSend(request) + return b.WebsocketSend(request) } func (b *Bitfinex) WebsocketSendAuth() error { From 4b559e5f4d239f1382fa271dee76a6f3bf645583 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 17 Apr 2017 15:01:46 +1000 Subject: [PATCH 31/37] Added websocket tests --- exchanges/bitfinex/bitfinex_websocket_test.go | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 exchanges/bitfinex/bitfinex_websocket_test.go diff --git a/exchanges/bitfinex/bitfinex_websocket_test.go b/exchanges/bitfinex/bitfinex_websocket_test.go new file mode 100644 index 00000000..eeaa6f95 --- /dev/null +++ b/exchanges/bitfinex/bitfinex_websocket_test.go @@ -0,0 +1,232 @@ +package bitfinex + +import ( + "net/http" + "testing" + + "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" +) + +func TestWebsocketPingHandler(t *testing.T) { + wsPingHandler := Bitfinex{} + var Dialer websocket.Dialer + var err error + + wsPingHandler.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{}) + if err != nil { + t.Errorf("Test Failed - Bitfinex dialer error: %s", err) + } + err = wsPingHandler.WebsocketPingHandler() + if err != nil { + t.Errorf("Test Failed - Bitfinex WebsocketPingHandler() error: %s", err) + } + err = wsPingHandler.WebsocketConn.Close() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketConn.Close() error: %s", err) + } +} + +func TestWebsocketSend(t *testing.T) { + wsSend := Bitfinex{} + var Dialer websocket.Dialer + var err error + + type WebsocketHandshake struct { + Event string `json:"event"` + Code int64 `json:"code"` + Version float64 `json:"version"` + } + + request, dodgyrequest := make(map[string]string), make(map[string]string) + request["event"] = "ping" + dodgyrequest["dodgyEvent"] = "didgereedodge" + + hs := WebsocketHandshake{} + + for { + wsSend.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{}) + if err != nil { + if err.Error() == "websocket: close 1006 (abnormal closure): unexpected EOF" { + err = wsSend.WebsocketConn.Close() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketConn.Close() error: %s", err) + } + continue + } else { + t.Errorf("Test Failed - Bitfinex websocket connection error: %s", err) + } + } + mType, resp, err := wsSend.WebsocketConn.ReadMessage() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketconn.ReadMessage() error: %s", err) + } + if mType != websocket.TextMessage { + t.Errorf("Test Failed - Bitfinex websocketconn.ReadMessage() mType error: %d", mType) + } + err = common.JSONDecode(resp, &hs) + if err != nil { + t.Errorf("Test Failed - Bitfinex JSONDecode error: %s", err) + } + if hs.Code != 0 { + t.Errorf("Test Failed - Bitfinex hs.Code incorrect: %d", hs.Code) + } + if hs.Event != "info" { + t.Errorf("Test Failed - Bitfinex hs.Event incorrect: %s", hs.Event) + } + if hs.Version != 1.1 { + t.Errorf("Test Failed - Bitfinex hs.Version incorrect: %f", hs.Version) + } + + err = wsSend.WebsocketSend(request) + if err != nil { + t.Errorf("Test Failed - Bitfinex websocket send error: %s", err) + } + mType, resp, err = wsSend.WebsocketConn.ReadMessage() + if err != nil { + if err.Error() == "websocket: close 1006 (abnormal closure): unexpected EOF" { + err = wsSend.WebsocketConn.Close() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketConn.Close() error: %s", err) + } + continue + } else { + t.Errorf("Test Failed - Bitfinex websocketConn.ReadMessage() error: %s", err) + } + } + if mType != websocket.TextMessage { + t.Errorf("Test Failed - Bitfinex websocketconn.ReadMessage() mType error: %d", mType) + } + err = common.JSONDecode(resp, &hs) + if err != nil { + t.Errorf("Test Failed - Bitfinex JSONDecode error: %s", err) + } + if hs.Code != 0 { + t.Errorf("Test Failed - Bitfinex hs.Code incorrect: %d", hs.Code) + } + if hs.Event != "pong" { + t.Errorf("Test Failed - Bitfinex hs.Event incorrect: %s", hs.Event) + } + if hs.Version != 1.1 { + t.Errorf("Test Failed - Bitfinex hs.Version incorrect: %f", hs.Version) + } + + err = wsSend.WebsocketSend(dodgyrequest) + if err != nil { + t.Errorf("Test Failed - Bitfinex websocket send error: %s", err) + } + mType, resp, err = wsSend.WebsocketConn.ReadMessage() + if err != nil { + if err.Error() == "websocket: close 1006 (abnormal closure): unexpected EOF" { + err = wsSend.WebsocketConn.Close() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketConn.Close() error: %s", err) + } + continue + } else { + t.Errorf("Test Failed - Bitfinex websocketConn.ReadMessage() error: %s", err) + } + } + if mType != websocket.TextMessage { + t.Errorf("Test Failed - Bitfinex websocketconn.ReadMessage() mType error: %d", mType) + } + err = common.JSONDecode(resp, &hs) + if err != nil { + t.Errorf("Test Failed - Bitfinex JSONDecode error: %s", err) + } + if hs.Code != 10000 { + t.Errorf("Test Failed - Bitfinex hs.Code incorrect: %d", hs.Code) + } + if hs.Event != "error" { + t.Errorf("Test Failed - Bitfinex hs.Event incorrect: %s", hs.Event) + } + if hs.Version != 1.1 { + t.Errorf("Test Failed - Bitfinex hs.Version incorrect: %f", hs.Version) + } + + err = wsSend.WebsocketConn.Close() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketConn.Close() error: %s", err) + } + break + } +} + +func TestWebsocketSubscribe(t *testing.T) { + websocketSubcribe := Bitfinex{} + var Dialer websocket.Dialer + var err error + params := make(map[string]string) + params["pair"] = "BTCUSD" + + websocketSubcribe.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{}) + if err != nil { + t.Errorf("Test Failed - Bitfinex Dialer error: %s", err) + } + err = websocketSubcribe.WebsocketSubscribe("ticker", params) + if err != nil { + t.Errorf("Test Failed - Bitfinex WebsocketSubscribe() error: %s", err) + } + + err = websocketSubcribe.WebsocketConn.Close() + if err != nil { + t.Errorf("Test Failed - Bitfinex websocketConn.Close() error: %s", err) + } +} + +func TestWebsocketSendAuth(t *testing.T) { + wsSendAuth := Bitfinex{} + var Dialer websocket.Dialer + var err error + + wsSendAuth.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{}) + if err != nil { + t.Errorf("Test Failed - Bitfinex Dialer error: %s", err) + } + err = wsSendAuth.WebsocketSendAuth() + if err != nil { + t.Errorf("Test Failed - Bitfinex WebsocketSendAuth() error: %s", err) + } +} + +func TestWebsocketSendUnauth(t *testing.T) { + wsSendUnauth := Bitfinex{} + var Dialer websocket.Dialer + var err error + + wsSendUnauth.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{}) + if err != nil { + t.Errorf("Test Failed - Bitfinex Dialer error: %s", err) + } + err = wsSendUnauth.WebsocketSendUnauth() + if err != nil { + t.Errorf("Test Failed - Bitfinex WebsocketSendAuth() error: %s", err) + } +} + +func TestWebsocketAddSubscriptionChannel(t *testing.T) { + wsAddSubscriptionChannel := Bitfinex{} + wsAddSubscriptionChannel.SetDefaults() + var Dialer websocket.Dialer + var err error + + wsAddSubscriptionChannel.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{}) + if err != nil { + t.Errorf("Test Failed - Bitfinex Dialer error: %s", err) + } + + wsAddSubscriptionChannel.WebsocketAddSubscriptionChannel(1337, "ticker", "BTCUSD") + if len(wsAddSubscriptionChannel.WebsocketSubdChannels) == 0 { + t.Errorf("Test Failed - Bitfinex WebsocketAddSubscriptionChannel() error: %s", err) + } + if wsAddSubscriptionChannel.WebsocketSubdChannels[1337].Channel != "ticker" { + t.Errorf("Test Failed - Bitfinex WebsocketAddSubscriptionChannel() error: %s", err) + } + if wsAddSubscriptionChannel.WebsocketSubdChannels[1337].Pair != "BTCUSD" { + t.Errorf("Test Failed - Bitfinex WebsocketAddSubscriptionChannel() error: %s", err) + } +} + +// func TestWebsocketClient(t *testing.T) { +// +// } From 44ca450d330c8255bf1515961e89df03195feb9a Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 17 Apr 2017 15:02:32 +1000 Subject: [PATCH 32/37] Added basic wrapper tests --- exchanges/bitfinex/bitfinex_wrapper_test.go | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 exchanges/bitfinex/bitfinex_wrapper_test.go diff --git a/exchanges/bitfinex/bitfinex_wrapper_test.go b/exchanges/bitfinex/bitfinex_wrapper_test.go new file mode 100644 index 00000000..f0ecc51c --- /dev/null +++ b/exchanges/bitfinex/bitfinex_wrapper_test.go @@ -0,0 +1,48 @@ +package bitfinex + +import ( + "testing" + + "github.com/thrasher-/gocryptotrader/config" +) + +func TestStart(t *testing.T) { + start := Bitfinex{} + start.Start() +} + +func TestRun(t *testing.T) { + run := Bitfinex{} + run.Run() +} + +func TestGetTickerPrice(t *testing.T) { + getTickerPrice := Bitfinex{} + _, err := getTickerPrice.GetTickerPrice("BTCUSD") + if err != nil { + t.Errorf("Test Failed - Bitfinex GetTickerPrice() error: %s", err) + } +} + +func TestGetOrderbookEx(t *testing.T) { + getOrderBookEx := Bitfinex{} + _, err := getOrderBookEx.GetOrderbookEx("BTCUSD") + if err != nil { + t.Errorf("Test Failed - Bitfinex GetOrderbookEx() error: %s", err) + } +} + +func TestGetExchangeAccountInfo(t *testing.T) { + getExchangeAccountInfo := Bitfinex{} + newConfig := config.GetConfig() + newConfig.LoadConfig("../../testdata/configtest.dat") + exchConf, err := newConfig.GetExchangeConfig("Bitfinex") + if err != nil { + t.Errorf("Test Failed - Bitfinex getExchangeConfig(): %s", err) + } + getExchangeAccountInfo.Setup(exchConf) + _, err = getExchangeAccountInfo.GetExchangeAccountInfo() + if err != nil { + t.Errorf("Test Failed - Bitfinex GetExchangeAccountInfo() error: %s", err) + } +} From 7e4a737f414e5f9a26f5213f7f0bacfd2ca080e2 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 18 Apr 2017 15:03:44 +1000 Subject: [PATCH 33/37] Fixed function --- config/config_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/config_test.go b/config/config_test.go index 305cf3c1..57a5c608 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -137,6 +137,6 @@ func TestSaveConfig(t *testing.T) { } err2 := saveConfig.SaveConfig("../testdata/configtest.dat") if err2 != nil { - t.Error("Test failed. TestSaveConfig.SaveConfig, %s", err2.Error()) + t.Errorf("Test failed. TestSaveConfig.SaveConfig, %s", err2.Error()) } } From 24adff9535452fd05db2e641b076309a07b522a7 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 18 Apr 2017 15:07:01 +1000 Subject: [PATCH 34/37] changed params --- exchanges/alphapoint/alphapoint_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exchanges/alphapoint/alphapoint_test.go b/exchanges/alphapoint/alphapoint_test.go index 91eef2a5..8319a4c4 100644 --- a/exchanges/alphapoint/alphapoint_test.go +++ b/exchanges/alphapoint/alphapoint_test.go @@ -395,7 +395,7 @@ func TestCreateAccount(t *testing.T) { CreateAccount := Alphapoint{} CreateAccount.SetDefaults() - err := CreateAccount.CreateAccount("test", "account", "oharareid.ryan@gmail.com", "0433588258", "lolcat123") + err := CreateAccount.CreateAccount("test", "account", "something@something.com", "0292383745", "lolcat123") if err != nil { t.Errorf("Test Failed - Init error: %s", err) } From 08ee4b0387910138dde194c081201b8d55829b3e Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 18 Apr 2017 15:10:12 +1000 Subject: [PATCH 35/37] Added error returns --- exchanges/anx/anx.go | 38 ++++++++++++++------------------------ 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/exchanges/anx/anx.go b/exchanges/anx/anx.go index 4b355f9c..0a23846e 100644 --- a/exchanges/anx/anx.go +++ b/exchanges/anx/anx.go @@ -61,9 +61,8 @@ func (a *ANX) Setup(exch config.ExchangeConfig) { func (a *ANX) GetFee(maker bool) float64 { if maker { return a.MakerFee - } else { - return a.TakerFee } + return a.TakerFee } func (a *ANX) GetTicker(currency string) (ANXTicker, error) { @@ -75,7 +74,7 @@ func (a *ANX) GetTicker(currency string) (ANXTicker, error) { return ticker, nil } -func (a *ANX) GetAPIKey(username, password, otp, deviceID string) (string, string) { +func (a *ANX) GetAPIKey(username, password, otp, deviceID string) (string, string, error) { request := make(map[string]interface{}) request["nonce"] = strconv.FormatInt(time.Now().UnixNano(), 10)[0:13] request["username"] = username @@ -96,21 +95,18 @@ func (a *ANX) GetAPIKey(username, password, otp, deviceID string) (string, strin var response APIKeyResponse err := a.SendAuthenticatedHTTPRequest(ANX_APIKEY, request, &response) - if err != nil { - log.Println(err) - return "", "" + return "", "", err } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) - return "", "" + return "", "", errors.New("Response code is not OK: " + response.ResultCode) } - return response.APIKey, response.APISecret + return response.APIKey, response.APISecret, nil } -func (a *ANX) GetDataToken() string { +func (a *ANX) GetDataToken() (string, error) { request := make(map[string]interface{}) type DataTokenResponse struct { @@ -122,22 +118,18 @@ func (a *ANX) GetDataToken() string { var response DataTokenResponse err := a.SendAuthenticatedHTTPRequest(ANX_DATA_TOKEN, request, &response) - if err != nil { - log.Println(err) - return "" + return "", err } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) - return "" + return "", errors.New("Response code is not OK: %s" + response.ResultCode) } - - return response.Token + return response.Token, nil } func (a *ANX) NewOrder(orderType string, buy bool, tradedCurrency, tradedCurrencyAmount, settlementCurrency, settlementCurrencyAmount, limitPriceSettlement string, - replace bool, replaceUUID string, replaceIfActive bool) { + replace bool, replaceUUID string, replaceIfActive bool) error { request := make(map[string]interface{}) var order ANXOrder @@ -169,16 +161,14 @@ func (a *ANX) NewOrder(orderType string, buy bool, tradedCurrency, tradedCurrenc var response OrderResponse err := a.SendAuthenticatedHTTPRequest(ANX_ORDER_NEW, request, &response) - if err != nil { - log.Println(err) - return + return err } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) - return + return errors.New("Response code is not OK: %s" + response.ResultCode) } + return nil } func (a *ANX) OrderInfo(orderID string) (ANXOrderResponse, error) { @@ -295,7 +285,7 @@ func (a *ANX) GetDepositAddress(currency, name string, new bool) (string, error) return response.Address, nil } -func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interface{}, result interface{}) (err error) { +func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interface{}, result interface{}) error { request := make(map[string]interface{}) request["nonce"] = strconv.FormatInt(time.Now().UnixNano(), 10)[0:13] path = fmt.Sprintf("api/%s/%s", ANX_API_VERSION, path) From c930d5105675a56f5f6495af59f0b133ff01d354 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 18 Apr 2017 15:11:31 +1000 Subject: [PATCH 36/37] Added string formatting --- main.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/main.go b/main.go index 9ea40d41..7e65dbde 100644 --- a/main.go +++ b/main.go @@ -145,7 +145,7 @@ func main() { err = currency.SeedCurrencyData(currency.BaseCurrencies) if err != nil { - log.Fatalf("Fatal error retrieving config currencies. Error: ", err) + log.Fatalf("Fatal error retrieving config currencies. Error: %s", err) } log.Println("Successfully retrieved config currencies.") @@ -246,5 +246,4 @@ func SeedExchangeAccountInfo(data []exchange.ExchangeAccountInfo) { } } } - } From b87c2dfa9f9718443af6f9a5089c45ccfd025d51 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Tue, 18 Apr 2017 15:19:36 +1000 Subject: [PATCH 37/37] Added Basic ANX tests --- exchanges/anx/anx_test.go | 146 ++++++++++++++++++++++++++++++ exchanges/anx/anx_wrapper_test.go | 25 +++++ 2 files changed, 171 insertions(+) create mode 100644 exchanges/anx/anx_test.go create mode 100644 exchanges/anx/anx_wrapper_test.go diff --git a/exchanges/anx/anx_test.go b/exchanges/anx/anx_test.go new file mode 100644 index 00000000..78529b94 --- /dev/null +++ b/exchanges/anx/anx_test.go @@ -0,0 +1,146 @@ +package anx + +import ( + "testing" + + "github.com/thrasher-/gocryptotrader/config" +) + +func TestSetDefaults(t *testing.T) { + setDefaults := ANX{} + setDefaults.SetDefaults() + + if setDefaults.Name != "ANX" { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } + if setDefaults.Enabled != false { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } + if setDefaults.TakerFee != 0.6 { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } + if setDefaults.MakerFee != 0.3 { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } + if setDefaults.Verbose != false { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } + if setDefaults.Websocket != false { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } + if setDefaults.RESTPollingDelay != 10 { + t.Error("Test Failed - ANX SetDefaults() incorrect values set") + } +} + +func TestSetup(t *testing.T) { + setup := ANX{} + anxSetupConfig := config.GetConfig() + anxSetupConfig.LoadConfig("../../testdata/configtest.dat") + anxConfig, err := anxSetupConfig.GetExchangeConfig("ANX") + if err != nil { + t.Error("Test Failed - ANX Setup() init error") + } + setup.Setup(anxConfig) + + if setup.Enabled != true { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if setup.AuthenticatedAPISupport != false { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if len(setup.APIKey) <= 0 { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if len(setup.APISecret) != 0 { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if setup.RESTPollingDelay != 10 { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if setup.Verbose != false { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if setup.Websocket != false { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if len(setup.BaseCurrencies) <= 0 { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if len(setup.AvailablePairs) <= 0 { + t.Error("Test Failed - ANX Setup() incorrect values set") + } + if len(setup.EnabledPairs) <= 0 { + t.Error("Test Failed - ANX Setup() incorrect values set") + } +} + +func TestGetFee(t *testing.T) { + getFee := ANX{} + makerFeeExpected, takerFeeExpected := 0.3, 0.6 + + getFee.SetDefaults() + if getFee.GetFee(true) != makerFeeExpected { + t.Error("Test Failed - ANX GetFee() incorrect return value") + } + if getFee.GetFee(false) != takerFeeExpected { + t.Error("Test Failed - ANX GetFee() incorrect return value") + } +} + +func TestGetTicker(t *testing.T) { + getTicker := ANX{} + ticker, err := getTicker.GetTicker("BTCUSD") + if err != nil { + t.Errorf("Test Failed - ANX GetTicker() error: %s", err) + } + if ticker.Result != "success" { + t.Error("Test Failed - ANX GetTicker() unsuccessful") + } +} + +func TestGetAPIKey(t *testing.T) { + getAPIKey := ANX{} + apiKey, apiSecret, err := getAPIKey.GetAPIKey("userName", "passWord", "", "1337") + if err == nil { + t.Error("Test Failed - ANX GetAPIKey() Incorrect") + } + if apiKey != "" { + t.Error("Test Failed - ANX GetAPIKey() Incorrect") + } + if apiSecret != "" { + t.Error("Test Failed - ANX GetAPIKey() Incorrect") + } +} + +func TestGetDataToken(t *testing.T) { + getDataToken := ANX{} + _, err := getDataToken.GetDataToken() + if err != nil { + t.Error("Test Failed - ANX GetDataToken() Incorrect") + } +} + +func TestNewOrder(t *testing.T) { + +} + +func TestOrderInfo(t *testing.T) { + +} + +func TestSend(t *testing.T) { + +} + +func TestCreateNewSubAccount(t *testing.T) { + +} + +func TestGetDepositAddress(t *testing.T) { + +} + +func TestSendAuthenticatedHTTPRequest(t *testing.T) { + +} diff --git a/exchanges/anx/anx_wrapper_test.go b/exchanges/anx/anx_wrapper_test.go new file mode 100644 index 00000000..cbc17f4c --- /dev/null +++ b/exchanges/anx/anx_wrapper_test.go @@ -0,0 +1,25 @@ +package anx + +import ( + "testing" +) + +func TestStart(t *testing.T) { + +} + +func TestRun(t *testing.T) { + +} + +func TestGetTickerPrice(t *testing.T) { + +} + +func TestGetOrderbookEx(t *testing.T) { + +} + +func TestGetExchangeAccountInfo(t *testing.T) { + +}