From e965e54e096f892cf21f6d24c466c8fb5f600d6e Mon Sep 17 00:00:00 2001 From: Adrian Gallagher Date: Tue, 4 Jun 2019 17:04:18 +1000 Subject: [PATCH] Split up common.go, file path fixes and much more --- .../common_templates/common_readme.tmpl | 2 +- cmd/documentation/documentation.go | 37 ++-- cmd/exchange_template/exchange_template.go | 41 ++-- cmd/exchange_template/main_file.tmpl | 6 +- common/README.md | 2 +- common/common.go | 108 +-------- common/common_test.go | 205 +----------------- common/convert/convert.go | 55 +++++ common/convert/convert_test.go | 96 ++++++++ communications/base/base.go | 6 +- communications/slack/slack.go | 15 +- communications/smsglobal/smsglobal.go | 6 +- communications/smtpservice/smtpservice.go | 3 +- communications/telegram/telegram.go | 15 +- config/config.go | 31 ++- currency/code.go | 9 +- currency/code_test.go | 72 +++--- currency/conversion_test.go | 13 +- currency/currencies.go | 10 +- currency/currency_test.go | 8 +- currency/forexprovider/base/base_interface.go | 3 +- .../currencyconverterapi.go | 9 +- .../currencylayer/currencylayer.go | 7 +- .../exchangeratesapi.io/exchangeratesapi.go | 4 +- currency/forexprovider/fixer.io/fixer.go | 7 +- .../openexchangerates/openexchangerates.go | 9 +- currency/pairs.go | 5 +- currency/storage.go | 4 +- engine/events/events.go | 24 +- engine/exchange.go | 2 +- engine/restful_router.go | 3 +- engine/routines.go | 3 +- engine/rpcserver.go | 17 +- engine/websocket.go | 3 +- exchanges/alphapoint/alphapoint.go | 3 +- exchanges/assets/assets.go | 4 +- exchanges/binance/binance.go | 23 +- exchanges/bitfinex/bitfinex_wrapper.go | 2 +- exchanges/bitflyer/bitflyer_wrapper.go | 5 +- exchanges/bithumb/bithumb.go | 37 ++-- exchanges/bithumb/bithumb_wrapper.go | 3 +- exchanges/bitmex/bitmex_parameters.go | 3 +- exchanges/bitmex/bitmex_websocket.go | 5 +- exchanges/bitstamp/bitstamp.go | 16 +- exchanges/bitstamp/bitstamp_websocket.go | 9 +- exchanges/bitstamp/bitstamp_wrapper.go | 3 +- exchanges/bittrex/bittrex.go | 10 +- exchanges/btcmarkets/btcmarkets.go | 23 +- exchanges/exchange.go | 3 +- exchanges/exchange_types.go | 5 +- exchanges/exmo/exmo.go | 2 +- exchanges/gateio/gateio.go | 15 +- exchanges/gateio/gateio_websocket.go | 10 +- exchanges/gemini/gemini.go | 4 +- exchanges/hitbtc/hitbtc_wrapper.go | 4 +- exchanges/huobi/huobi_websocket.go | 13 +- exchanges/huobi/huobi_wrapper.go | 2 +- exchanges/huobihadax/huobihadax.go | 3 +- exchanges/huobihadax/huobihadax_websocket.go | 13 +- exchanges/huobihadax/huobihadax_wrapper.go | 2 +- exchanges/kraken/kraken.go | 5 +- exchanges/kraken/kraken_wrapper.go | 6 +- exchanges/lakebtc/lakebtc.go | 12 +- exchanges/lakebtc/lakebtc_wrapper.go | 2 +- exchanges/localbitcoins/localbitcoins.go | 2 +- exchanges/request/request.go | 3 +- exchanges/ticker/ticker.go | 4 +- exchanges/websocket_test.go | 4 +- exchanges/yobit/yobit_wrapper.go | 2 +- exchanges/zb/zb.go | 5 +- exchanges/zb/zb_websocket.go | 15 +- exchanges/zb/zb_wrapper.go | 5 +- portfolio/portfolio.go | 9 +- utils/utils.go | 5 +- 74 files changed, 524 insertions(+), 617 deletions(-) create mode 100644 common/convert/convert.go create mode 100644 common/convert/convert_test.go diff --git a/cmd/documentation/common_templates/common_readme.tmpl b/cmd/documentation/common_templates/common_readme.tmpl index fb3f828e..71db2823 100644 --- a/cmd/documentation/common_templates/common_readme.tmpl +++ b/cmd/documentation/common_templates/common_readme.tmpl @@ -11,7 +11,7 @@ import "github.com/thrasher-/gocryptotrader/common" testString := "aAaAa" -upper := common.StringToUpper(testString) +upper := strings.ToUpper(testString) // upper == "AAAAA" ``` diff --git a/cmd/documentation/documentation.go b/cmd/documentation/documentation.go index d484ea13..b5d348d3 100644 --- a/cmd/documentation/documentation.go +++ b/cmd/documentation/documentation.go @@ -6,6 +6,7 @@ import ( "html/template" "log" "os" + "runtime" "strings" "time" @@ -118,7 +119,7 @@ func main() { codebasePaths = make(map[string]string) codebaseTemplatePath = make(map[string]string) codebaseReadme = make(map[string]readme) - path = common.GetOSPathSlash() + path = getOSPathSlash() if err := getContributorList(); err != nil { log.Fatal("GoCryptoTrader: Exchange documentation tool GET error ", err) @@ -139,6 +140,16 @@ func main() { fmt.Println("\nTool finished") } +// getOSPathSlash returns the slash used by the operating systems +// file system +// TO-DO: Change all paths to not use this +func getOSPathSlash() string { + if runtime.GOOS == "windows" { + return "\\" + } + return "/" +} + // updateReadme iterates through codebase paths to check for readme files and either adds // or replaces with new readme files. func updateReadme() error { @@ -295,18 +306,18 @@ func getslashFromName(packageName string) string { } var globS = []string{ - fmt.Sprintf("common_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("communications_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("config_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("currency_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("events_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("exchanges_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("portfolio_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("root_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("sub_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("testdata_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("tools_templates%s*", common.GetOSPathSlash()), - fmt.Sprintf("web_templates%s*", common.GetOSPathSlash()), + fmt.Sprintf("common_templates%s*", getOSPathSlash()), + fmt.Sprintf("communications_templates%s*", getOSPathSlash()), + fmt.Sprintf("config_templates%s*", getOSPathSlash()), + fmt.Sprintf("currency_templates%s*", getOSPathSlash()), + fmt.Sprintf("events_templates%s*", getOSPathSlash()), + fmt.Sprintf("exchanges_templates%s*", getOSPathSlash()), + fmt.Sprintf("portfolio_templates%s*", getOSPathSlash()), + fmt.Sprintf("root_templates%s*", getOSPathSlash()), + fmt.Sprintf("sub_templates%s*", getOSPathSlash()), + fmt.Sprintf("testdata_templates%s*", getOSPathSlash()), + fmt.Sprintf("tools_templates%s*", getOSPathSlash()), + fmt.Sprintf("web_templates%s*", getOSPathSlash()), } // addTemplates adds all the template files diff --git a/cmd/exchange_template/exchange_template.go b/cmd/exchange_template/exchange_template.go index bce03308..d7e44f7f 100644 --- a/cmd/exchange_template/exchange_template.go +++ b/cmd/exchange_template/exchange_template.go @@ -7,12 +7,13 @@ import ( "log" "os" "os/exec" - - "github.com/thrasher-/gocryptotrader/currency" - "github.com/thrasher-/gocryptotrader/exchanges/assets" + "path/filepath" + "strings" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" + "github.com/thrasher-/gocryptotrader/currency" + "github.com/thrasher-/gocryptotrader/exchanges/assets" ) const ( @@ -22,9 +23,9 @@ const ( packageMain = "%s.go" packageReadme = "README.md" - exchangePackageLocation = "..%s..%sexchanges%s" - exchangeLocation = "..%s..%sexchange.go" - exchangeConfigPath = "..%s..%stestdata%sconfigtest.json" + exchangePackageLocation = "../../exchanges" + exchangeLocation = "../../exchange.go" + exchangeConfigPath = "../../testdata/configtest.json" ) var ( @@ -84,9 +85,9 @@ func main() { log.Fatal("GoCryptoTrader: Exchange templating tool stopped...") } - newExchangeName = common.StringToLower(newExchangeName) + newExchangeName = strings.ToLower(newExchangeName) v := newExchangeName[:1] - capName := common.StringToUpper(v) + newExchangeName[1:] + capName := strings.ToUpper(v) + newExchangeName[1:] exch := exchange{ Name: newExchangeName, @@ -97,18 +98,14 @@ func main() { FIX: fixSupport, } - osPathSlash := common.GetOSPathSlash() - exchangeJSON := fmt.Sprintf(exchangeConfigPath, osPathSlash, osPathSlash, osPathSlash) - configTestFile := config.GetConfig() - err = configTestFile.LoadConfig(exchangeJSON) + err = configTestFile.LoadConfig(exchangeConfigPath) if err != nil { log.Fatal("GoCryptoTrader: Exchange templating configuration retrieval error ", err) } // NOTE need to nullify encrypt configuration var configTestExchanges []string - for x := range configTestFile.Exchanges { configTestExchanges = append(configTestExchanges, configTestFile.Exchanges[x].Name) } @@ -137,18 +134,12 @@ func main() { log.Fatal("GoCryptoTrader: Exchange templating configuration error - cannot save") } - exchangeDirectory = fmt.Sprintf( - exchangePackageLocation+newExchangeName+"%s", - osPathSlash, - osPathSlash, - osPathSlash, - osPathSlash) - - exchangeTest = fmt.Sprintf(exchangeDirectory+packageTests, newExchangeName) - exchangeTypes = fmt.Sprintf(exchangeDirectory+packageTypes, newExchangeName) - exchangeWrapper = fmt.Sprintf(exchangeDirectory+packageWrapper, newExchangeName) - exchangeMain = fmt.Sprintf(exchangeDirectory+packageMain, newExchangeName) - exchangeReadme = exchangeDirectory + packageReadme + exchangeDirectory = filepath.Join(exchangePackageLocation, newExchangeName) + exchangeTest = filepath.Join(exchangeDirectory, fmt.Sprintf(packageTests, newExchangeName)) + exchangeTypes = filepath.Join(exchangeDirectory, fmt.Sprintf(packageTypes, newExchangeName)) + exchangeWrapper = filepath.Join(exchangeDirectory, fmt.Sprintf(packageWrapper, newExchangeName)) + exchangeMain = filepath.Join(exchangeDirectory, fmt.Sprintf(packageMain, newExchangeName)) + exchangeReadme = filepath.Join(exchangeDirectory, packageReadme) err = os.Mkdir(exchangeDirectory, 0700) if err != nil { diff --git a/cmd/exchange_template/main_file.tmpl b/cmd/exchange_template/main_file.tmpl index 024711dc..242b633c 100644 --- a/cmd/exchange_template/main_file.tmpl +++ b/cmd/exchange_template/main_file.tmpl @@ -60,9 +60,9 @@ func ({{.Variable}} *{{.CapitalName}}) Setup(exch *config.ExchangeConfig) error {{.Variable}}.SetHTTPClientUserAgent(exch.HTTPUserAgent) {{.Variable}}.Verbose = exch.Verbose {{.Variable}}.Websocket.SetWsStatusAndConnection(exch.Features.Enabled.Websocket) - {{.Variable}}.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") - {{.Variable}}.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") - {{.Variable}}.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") + {{.Variable}}.BaseCurrencies = strings.Split(exch.BaseCurrencies, ",") + {{.Variable}}.AvailablePairs = strings.Split(exch.AvailablePairs, ",") + {{.Variable}}.EnabledPairs = strings.Split(exch.EnabledPairs, ",") err := {{.Variable}}.SetCurrencyPairFormat() if err != nil { log.Fatal(err) diff --git a/common/README.md b/common/README.md index 3720ba1c..70004ef8 100644 --- a/common/README.md +++ b/common/README.md @@ -29,7 +29,7 @@ import "github.com/thrasher-/gocryptotrader/common" testString := "aAaAa" -upper := common.StringToUpper(testString) +upper := strings.ToUpper(testString) // upper == "AAAAA" ``` diff --git a/common/common.go b/common/common.go index 426317d6..f2af18db 100644 --- a/common/common.go +++ b/common/common.go @@ -14,7 +14,6 @@ import ( "path/filepath" "reflect" "regexp" - "runtime" "strconv" "strings" "time" @@ -81,12 +80,6 @@ func StringSliceDifference(slice1, slice2 []string) []string { return diff } -// StringContains checks a substring if it contains your input then returns a -// bool -func StringContains(input, substring string) bool { - return strings.Contains(input, substring) -} - // StringDataContains checks the substring array with an input and returns a bool func StringDataContains(haystack []string, needle string) bool { data := strings.Join(haystack, ",") @@ -118,45 +111,13 @@ func StringDataCompareInsensitive(haystack []string, needle string) bool { // a bool irrespective of lower or upper case strings func StringDataContainsInsensitive(haystack []string, needle string) bool { for _, data := range haystack { - if strings.Contains(StringToUpper(data), StringToUpper(needle)) { + if strings.Contains(strings.ToUpper(data), strings.ToUpper(needle)) { return true } } return false } -// JoinStrings joins an array together with the required separator and returns -// it as a string -func JoinStrings(input []string, separator string) string { - return strings.Join(input, separator) -} - -// SplitStrings splits blocks of strings from string into a string array using -// a separator ie "," or "_" -func SplitStrings(input, separator string) []string { - return strings.Split(input, separator) -} - -// TrimString trims unwanted prefixes or postfixes -func TrimString(input, cutset string) string { - return strings.Trim(input, cutset) -} - -// ReplaceString replaces a string with another -func ReplaceString(input, old, newStr string, n int) string { - return strings.Replace(input, old, newStr, n) -} - -// StringToUpper changes strings to uppercase -func StringToUpper(input string) string { - return strings.ToUpper(input) -} - -// StringToLower changes strings to lowercase -func StringToLower(input string) string { - return strings.ToLower(input) -} - // IsEnabled takes in a boolean param and returns a string if it is enabled // or disabled func IsEnabled(isEnabled bool) string { @@ -170,7 +131,7 @@ func IsEnabled(isEnabled bool) string { // regexp package // Validation issues occurring because "3" is contained in // litecoin and Bitcoin addresses - non-fatal func IsValidCryptoAddress(address, crypto string) (bool, error) { - switch StringToLower(crypto) { + switch strings.ToLower(crypto) { case "btc": return regexp.MatchString("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$", address) case "ltc": @@ -184,7 +145,7 @@ func IsValidCryptoAddress(address, crypto string) (bool, error) { // YesOrNo returns a boolean variable to check if input is "y" or "yes" func YesOrNo(input string) bool { - if StringToLower(input) == "y" || StringToLower(input) == "yes" { + if strings.ToLower(input) == "y" || strings.ToLower(input) == "yes" { return true } return false @@ -276,7 +237,7 @@ func JSONEncode(v interface{}) ([]byte, error) { // JSONDecode decodes JSON data into a structure func JSONDecode(data []byte, to interface{}) error { - if !StringContains(reflect.ValueOf(to).Type().String(), "*") { + if !strings.Contains(reflect.ValueOf(to).Type().String(), "*") { return errors.New("json decode error - memory address not supplied") } return json.Unmarshal(data, to) @@ -294,7 +255,7 @@ func EncodeURLValues(urlPath string, values url.Values) string { // ExtractHost returns the hostname out of a string func ExtractHost(address string) string { - host := SplitStrings(address, ":")[0] + host := strings.Split(address, ":")[0] if host == "" { return "localhost" } @@ -303,7 +264,7 @@ func ExtractHost(address string) string { // ExtractPort returns the port name out of a string func ExtractPort(host string) int { - portStr := SplitStrings(host, ":")[1] + portStr := strings.Split(host, ":")[1] port, _ := strconv.Atoi(portStr) return port } @@ -386,15 +347,6 @@ func GetExecutablePath() (string, error) { return filepath.Dir(ex), nil } -// GetOSPathSlash returns the slash used by the operating systems -// file system -func GetOSPathSlash() string { - if runtime.GOOS == "windows" { - return "\\" - } - return "/" -} - // UnixMillis converts a UnixNano timestamp to milliseconds func UnixMillis(t time.Time) int64 { return t.UnixNano() / int64(time.Millisecond) @@ -405,54 +357,6 @@ func RecvWindow(d time.Duration) int64 { return int64(d) / int64(time.Millisecond) } -// FloatFromString format -func FloatFromString(raw interface{}) (float64, error) { - str, ok := raw.(string) - if !ok { - return 0, fmt.Errorf("unable to parse, value not string: %T", raw) - } - flt, err := strconv.ParseFloat(str, 64) - if err != nil { - return 0, fmt.Errorf("could not convert value: %s Error: %s", str, err) - } - return flt, nil -} - -// IntFromString format -func IntFromString(raw interface{}) (int, error) { - str, ok := raw.(string) - if !ok { - return 0, fmt.Errorf("unable to parse, value not string: %T", raw) - } - n, err := strconv.Atoi(str) - if err != nil { - return 0, fmt.Errorf("unable to parse as int: %T", raw) - } - return n, nil -} - -// Int64FromString format -func Int64FromString(raw interface{}) (int64, error) { - str, ok := raw.(string) - if !ok { - return 0, fmt.Errorf("unable to parse, value not string: %T", raw) - } - n, err := strconv.ParseInt(str, 10, 64) - if err != nil { - return 0, fmt.Errorf("unable to parse as int64: %T", raw) - } - return n, nil -} - -// TimeFromUnixTimestampFloat format -func TimeFromUnixTimestampFloat(raw interface{}) (time.Time, error) { - ts, ok := raw.(float64) - if !ok { - return time.Time{}, fmt.Errorf("unable to parse, value not float64: %T", raw) - } - return time.Unix(0, int64(ts)*int64(time.Millisecond)), nil -} - // GetDefaultDataDir returns the default data directory // Windows - C:\Users\%USER%\AppData\Roaming\GoCryptoTrader // Linux/Unix or OSX - $HOME/.gocryptotrader diff --git a/common/common_test.go b/common/common_test.go index 16d73227..97dc144c 100644 --- a/common/common_test.go +++ b/common/common_test.go @@ -73,28 +73,6 @@ func TestIsValidCryptoAddress(t *testing.T) { } } -func TestStringToLower(t *testing.T) { - t.Parallel() - upperCaseString := "HEY MAN" - expectedResult := "hey man" - actualResult := StringToLower(upperCaseString) - if actualResult != expectedResult { - t.Errorf("Test failed. Expected '%s'. Actual '%s'", - expectedResult, actualResult) - } -} - -func TestStringToUpper(t *testing.T) { - t.Parallel() - upperCaseString := "hey man" - expectedResult := "HEY MAN" - actualResult := StringToUpper(upperCaseString) - if actualResult != expectedResult { - t.Errorf("Test failed. Expected '%s'. Actual '%s'", - expectedResult, actualResult) - } -} - func TestStringSliceDifference(t *testing.T) { t.Parallel() originalInputOne := []string{"hello"} @@ -107,18 +85,6 @@ func TestStringSliceDifference(t *testing.T) { } } -func TestStringContains(t *testing.T) { - t.Parallel() - originalInput := "hello" - originalInputSubstring := "he" - expectedOutput := true - actualResult := StringContains(originalInput, originalInputSubstring) - if actualResult != expectedOutput { - t.Errorf("Test failed. Expected '%v'. Actual '%v'", - expectedOutput, actualResult) - } -} - func TestStringDataContains(t *testing.T) { t.Parallel() originalHaystack := []string{"hello", "world", "USDT", "Contains", "string"} @@ -196,64 +162,6 @@ func TestStringDataContainsUpper(t *testing.T) { } } -func TestJoinStrings(t *testing.T) { - t.Parallel() - originalInputOne := []string{"hello", "moto"} - separator := "," - expectedOutput := "hello,moto" - actualResult := JoinStrings(originalInputOne, separator) - if expectedOutput != actualResult { - t.Errorf("Test failed. Expected '%s'. Actual '%s'", - expectedOutput, actualResult) - } -} - -func TestSplitStrings(t *testing.T) { - t.Parallel() - originalInputOne := "hello,moto" - separator := "," - expectedOutput := []string{"hello", "moto"} - actualResult := SplitStrings(originalInputOne, separator) - if !reflect.DeepEqual(expectedOutput, actualResult) { - t.Errorf("Test failed. Expected '%s'. Actual '%s'", - expectedOutput, actualResult) - } -} - -func TestTrimString(t *testing.T) { - t.Parallel() - originalInput := "abcd" - cutset := "ad" - expectedOutput := "bc" - actualResult := TrimString(originalInput, cutset) - if expectedOutput != actualResult { - t.Errorf("Test failed. Expected '%s'. Actual '%s'", - expectedOutput, actualResult) - } -} - -// TestReplaceString replaces a string with another -func TestReplaceString(t *testing.T) { - t.Parallel() - currency := "BTC-USD" - expectedOutput := "BTCUSD" - - actualResult := ReplaceString(currency, "-", "", -1) - if expectedOutput != actualResult { - t.Errorf( - "Test failed. Expected '%s'. Actual '%s'", expectedOutput, actualResult, - ) - } - - currency = "BTC-USD--" - actualResult = ReplaceString(currency, "-", "", 3) - if expectedOutput != actualResult { - t.Errorf( - "Test failed. Expected '%s'. Actual '%s'", expectedOutput, actualResult, - ) - } -} - func TestYesOrNo(t *testing.T) { t.Parallel() if !YesOrNo("y") { @@ -580,14 +488,6 @@ func TestGetExecutablePath(t *testing.T) { } } -func TestGetOSPathSlash(t *testing.T) { - output := GetOSPathSlash() - if output != "/" && output != "\\" { - t.Errorf("Test failed. Common GetOSPathSlash. Returned '%s'", output) - } - -} - func TestUnixMillis(t *testing.T) { t.Parallel() testTime := time.Date(2014, time.October, 28, 0, 32, 0, 0, time.UTC) @@ -612,96 +512,6 @@ func TestRecvWindow(t *testing.T) { } } -func TestFloatFromString(t *testing.T) { - t.Parallel() - testString := "1.41421356237" - expectedOutput := float64(1.41421356237) - - actualOutput, err := FloatFromString(testString) - if actualOutput != expectedOutput || err != nil { - t.Errorf("Test failed. Common FloatFromString. Expected '%v'. Actual '%v'. Error: %s", - expectedOutput, actualOutput, err) - } - - var testByte []byte - _, err = FloatFromString(testByte) - if err == nil { - t.Error("Test failed. Common FloatFromString. Converted non-string.") - } - - testString = " something unconvertible " - _, err = FloatFromString(testString) - if err == nil { - t.Error("Test failed. Common FloatFromString. Converted invalid syntax.") - } -} - -func TestIntFromString(t *testing.T) { - t.Parallel() - testString := "1337" - expectedOutput := 1337 - - actualOutput, err := IntFromString(testString) - if actualOutput != expectedOutput || err != nil { - t.Errorf("Test failed. Common IntFromString. Expected '%v'. Actual '%v'. Error: %s", - expectedOutput, actualOutput, err) - } - - var testByte []byte - _, err = IntFromString(testByte) - if err == nil { - t.Error("Test failed. Common IntFromString. Converted non-string.") - } - - testString = "1.41421356237" - _, err = IntFromString(testString) - if err == nil { - t.Error("Test failed. Common IntFromString. Converted invalid syntax.") - } -} - -func TestInt64FromString(t *testing.T) { - t.Parallel() - testString := "4398046511104" - expectedOutput := int64(1 << 42) - - actualOutput, err := Int64FromString(testString) - if actualOutput != expectedOutput || err != nil { - t.Errorf("Test failed. Common Int64FromString. Expected '%v'. Actual '%v'. Error: %s", - expectedOutput, actualOutput, err) - } - - var testByte []byte - _, err = Int64FromString(testByte) - if err == nil { - t.Error("Test failed. Common Int64FromString. Converted non-string.") - } - - testString = "1.41421356237" - _, err = Int64FromString(testString) - if err == nil { - t.Error("Test failed. Common Int64FromString. Converted invalid syntax.") - } -} - -func TestTimeFromUnixTimestampFloat(t *testing.T) { - t.Parallel() - testTimestamp := float64(1414456320000) - expectedOutput := time.Date(2014, time.October, 28, 0, 32, 0, 0, time.UTC) - - actualOutput, err := TimeFromUnixTimestampFloat(testTimestamp) - if actualOutput.UTC().String() != expectedOutput.UTC().String() || err != nil { - t.Errorf("Test failed. Common TimeFromUnixTimestampFloat. Expected '%v'. Actual '%v'. Error: %s", - expectedOutput, actualOutput, err) - } - - testString := "Time" - _, err = TimeFromUnixTimestampFloat(testString) - if err == nil { - t.Error("Test failed. Common TimeFromUnixTimestampFloat. Converted invalid syntax.") - } -} - func TestGetDefaultDataDir(t *testing.T) { switch runtime.GOOS { case "windows": @@ -758,7 +568,7 @@ func TestCreateDir(t *testing.T) { if !ok { t.Fatal("LookupEnv failed. APPDATA is not set") } - dir = dir + GetOSPathSlash() + "GoCryptoTrader\\TestFileASDFG" + dir = filepath.Join(dir, "GoCryptoTrader", "TestFileASDFG") err = CreateDir(dir) if err != nil { t.Fatalf("CreateDir failed. Err: %v", err) @@ -796,13 +606,14 @@ func TestCreateDir(t *testing.T) { } func TestChangePerm(t *testing.T) { + testDir := filepath.Join(GetDefaultDataDir(runtime.GOOS), "TestFileASDFGHJ") switch runtime.GOOS { case "windows": err := ChangePerm("*") if err == nil { t.Fatal("expected an error on non-existent path") } - err = os.Mkdir(GetDefaultDataDir(runtime.GOOS)+GetOSPathSlash()+"TestFileASDFGHJ", 0777) + err = os.Mkdir(testDir, 0777) if err != nil { t.Fatalf("Mkdir failed. Err: %v", err) } @@ -810,11 +621,11 @@ func TestChangePerm(t *testing.T) { if err != nil { t.Fatalf("ChangePerm was unsuccessful. Err: %v", err) } - _, err = os.Stat(GetDefaultDataDir(runtime.GOOS) + GetOSPathSlash() + "TestFileASDFGHJ") + _, err = os.Stat(testDir) if err != nil { t.Fatalf("os.Stat failed. Err: %v", err) } - err = RemoveFile(GetDefaultDataDir(runtime.GOOS) + GetOSPathSlash() + "TestFileASDFGHJ") + err = RemoveFile(testDir) if err != nil { t.Fatalf("RemoveFile failed. Err: %v", err) } @@ -823,7 +634,7 @@ func TestChangePerm(t *testing.T) { if err == nil { t.Fatal("expected an error on non-existent path") } - err = os.Mkdir(GetDefaultDataDir(runtime.GOOS)+GetOSPathSlash()+"TestFileASDFGHJ", 0777) + err = os.Mkdir(testDir, 0777) if err != nil { t.Fatalf("Mkdir failed. Err: %v", err) } @@ -832,14 +643,14 @@ func TestChangePerm(t *testing.T) { t.Fatalf("ChangePerm was unsuccessful. Err: %v", err) } var a os.FileInfo - a, err = os.Stat(GetDefaultDataDir(runtime.GOOS) + GetOSPathSlash() + "TestFileASDFGHJ") + a, err = os.Stat(testDir) if err != nil { t.Fatalf("os.Stat failed. Err: %v", err) } if a.Mode().Perm() != 0770 { t.Fatalf("expected file permissions differ. expecting 0770 got %#o", a.Mode().Perm()) } - err = RemoveFile(GetDefaultDataDir(runtime.GOOS) + GetOSPathSlash() + "TestFileASDFGHJ") + err = RemoveFile(testDir) if err != nil { t.Fatalf("RemoveFile failed. Err: %v", err) } diff --git a/common/convert/convert.go b/common/convert/convert.go new file mode 100644 index 00000000..27c6b1cf --- /dev/null +++ b/common/convert/convert.go @@ -0,0 +1,55 @@ +package convert + +import ( + "fmt" + "strconv" + "time" +) + +// FloatFromString format +func FloatFromString(raw interface{}) (float64, error) { + str, ok := raw.(string) + if !ok { + return 0, fmt.Errorf("unable to parse, value not string: %T", raw) + } + flt, err := strconv.ParseFloat(str, 64) + if err != nil { + return 0, fmt.Errorf("could not convert value: %s Error: %s", str, err) + } + return flt, nil +} + +// IntFromString format +func IntFromString(raw interface{}) (int, error) { + str, ok := raw.(string) + if !ok { + return 0, fmt.Errorf("unable to parse, value not string: %T", raw) + } + n, err := strconv.Atoi(str) + if err != nil { + return 0, fmt.Errorf("unable to parse as int: %T", raw) + } + return n, nil +} + +// Int64FromString format +func Int64FromString(raw interface{}) (int64, error) { + str, ok := raw.(string) + if !ok { + return 0, fmt.Errorf("unable to parse, value not string: %T", raw) + } + n, err := strconv.ParseInt(str, 10, 64) + if err != nil { + return 0, fmt.Errorf("unable to parse as int64: %T", raw) + } + return n, nil +} + +// TimeFromUnixTimestampFloat format +func TimeFromUnixTimestampFloat(raw interface{}) (time.Time, error) { + ts, ok := raw.(float64) + if !ok { + return time.Time{}, fmt.Errorf("unable to parse, value not float64: %T", raw) + } + return time.Unix(0, int64(ts)*int64(time.Millisecond)), nil +} diff --git a/common/convert/convert_test.go b/common/convert/convert_test.go new file mode 100644 index 00000000..c3aef95a --- /dev/null +++ b/common/convert/convert_test.go @@ -0,0 +1,96 @@ +package convert + +import ( + "testing" + "time" +) + +func TestFloatFromString(t *testing.T) { + t.Parallel() + testString := "1.41421356237" + expectedOutput := float64(1.41421356237) + + actualOutput, err := FloatFromString(testString) + if actualOutput != expectedOutput || err != nil { + t.Errorf("Test failed. Common FloatFromString. Expected '%v'. Actual '%v'. Error: %s", + expectedOutput, actualOutput, err) + } + + var testByte []byte + _, err = FloatFromString(testByte) + if err == nil { + t.Error("Test failed. Common FloatFromString. Converted non-string.") + } + + testString = " something unconvertible " + _, err = FloatFromString(testString) + if err == nil { + t.Error("Test failed. Common FloatFromString. Converted invalid syntax.") + } +} + +func TestIntFromString(t *testing.T) { + t.Parallel() + testString := "1337" + expectedOutput := 1337 + + actualOutput, err := IntFromString(testString) + if actualOutput != expectedOutput || err != nil { + t.Errorf("Test failed. Common IntFromString. Expected '%v'. Actual '%v'. Error: %s", + expectedOutput, actualOutput, err) + } + + var testByte []byte + _, err = IntFromString(testByte) + if err == nil { + t.Error("Test failed. Common IntFromString. Converted non-string.") + } + + testString = "1.41421356237" + _, err = IntFromString(testString) + if err == nil { + t.Error("Test failed. Common IntFromString. Converted invalid syntax.") + } +} + +func TestInt64FromString(t *testing.T) { + t.Parallel() + testString := "4398046511104" + expectedOutput := int64(1 << 42) + + actualOutput, err := Int64FromString(testString) + if actualOutput != expectedOutput || err != nil { + t.Errorf("Test failed. Common Int64FromString. Expected '%v'. Actual '%v'. Error: %s", + expectedOutput, actualOutput, err) + } + + var testByte []byte + _, err = Int64FromString(testByte) + if err == nil { + t.Error("Test failed. Common Int64FromString. Converted non-string.") + } + + testString = "1.41421356237" + _, err = Int64FromString(testString) + if err == nil { + t.Error("Test failed. Common Int64FromString. Converted invalid syntax.") + } +} + +func TestTimeFromUnixTimestampFloat(t *testing.T) { + t.Parallel() + testTimestamp := float64(1414456320000) + expectedOutput := time.Date(2014, time.October, 28, 0, 32, 0, 0, time.UTC) + + actualOutput, err := TimeFromUnixTimestampFloat(testTimestamp) + if actualOutput.UTC().String() != expectedOutput.UTC().String() || err != nil { + t.Errorf("Test failed. Common TimeFromUnixTimestampFloat. Expected '%v'. Actual '%v'. Error: %s", + expectedOutput, actualOutput, err) + } + + testString := "Time" + _, err = TimeFromUnixTimestampFloat(testString) + if err == nil { + t.Error("Test failed. Common TimeFromUnixTimestampFloat. Converted invalid syntax.") + } +} diff --git a/communications/base/base.go b/communications/base/base.go index 5a6701fd..cd047aea 100644 --- a/communications/base/base.go +++ b/communications/base/base.go @@ -2,10 +2,10 @@ package base import ( "fmt" + "strings" "sync" "time" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/exchanges/assets" "github.com/thrasher-/gocryptotrader/exchanges/ticker" ) @@ -112,7 +112,7 @@ func (b *Base) GetTicker(exchangeName string) string { tickerPrices[i].PriceATH, tickerPrices[i].Volume)) } - return common.JoinStrings(packagedTickers, "\n") + return strings.Join(packagedTickers, "\n") } // GetOrderbook returns staged orderbook data @@ -142,7 +142,7 @@ func (b *Base) GetOrderbook(exchangeName string) string { orderbooks[i].TotalAsks, orderbooks[i].TotalBids)) } - return common.JoinStrings(packagedOrderbooks, "\n") + return strings.Join(packagedOrderbooks, "\n") } // GetPortfolio returns staged portfolio info diff --git a/communications/slack/slack.go b/communications/slack/slack.go index 3627455c..444ee9c6 100644 --- a/communications/slack/slack.go +++ b/communications/slack/slack.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net/http" + "strings" "sync" "time" @@ -364,24 +365,24 @@ func (s *Slack) HandleMessage(msg *Message) error { return errors.New("msg is nil") } - msg.Text = common.StringToLower(msg.Text) + msg.Text = strings.ToLower(msg.Text) switch { - case common.StringContains(msg.Text, cmdStatus): + case strings.Contains(msg.Text, cmdStatus): return s.WebsocketSend("message", s.GetStatus()) - case common.StringContains(msg.Text, cmdHelp): + case strings.Contains(msg.Text, cmdHelp): return s.WebsocketSend("message", getHelp) - case common.StringContains(msg.Text, cmdTicker): + case strings.Contains(msg.Text, cmdTicker): return s.WebsocketSend("message", s.GetTicker("ANX")) - case common.StringContains(msg.Text, cmdOrderbook): + case strings.Contains(msg.Text, cmdOrderbook): return s.WebsocketSend("message", s.GetOrderbook("ANX")) - case common.StringContains(msg.Text, cmdSettings): + case strings.Contains(msg.Text, cmdSettings): return s.WebsocketSend("message", s.GetSettings()) - case common.StringContains(msg.Text, cmdPortfolio): + case strings.Contains(msg.Text, cmdPortfolio): return s.WebsocketSend("message", s.GetPortfolio()) default: diff --git a/communications/smsglobal/smsglobal.go b/communications/smsglobal/smsglobal.go index 2d23c44e..2157c663 100644 --- a/communications/smsglobal/smsglobal.go +++ b/communications/smsglobal/smsglobal.go @@ -89,7 +89,7 @@ func (s *SMSGlobal) GetContactByNumber(number string) (Contact, error) { // GetContactByName returns a contact with supplied name func (s *SMSGlobal) GetContactByName(name string) (Contact, error) { for x := range s.Contacts { - if common.StringToLower(s.Contacts[x].Name) == common.StringToLower(name) { + if strings.ToLower(s.Contacts[x].Name) == strings.ToLower(name) { return s.Contacts[x], nil } } @@ -113,7 +113,7 @@ func (s *SMSGlobal) AddContact(contact Contact) error { // ContactExists checks to see if a contact exists func (s *SMSGlobal) ContactExists(contact Contact) bool { for x := range s.Contacts { - if s.Contacts[x].Number == contact.Number && common.StringToLower(s.Contacts[x].Name) == common.StringToLower(contact.Name) { + if s.Contacts[x].Number == contact.Number && strings.ToLower(s.Contacts[x].Name) == strings.ToLower(contact.Name) { return true } } @@ -173,7 +173,7 @@ func (s *SMSGlobal) SendMessage(to, message string) error { return err } - if !common.StringContains(resp, "OK: 0; Sent queued message") { + if !strings.Contains(resp, "OK: 0; Sent queued message") { return errSMSNotSent } return nil diff --git a/communications/smtpservice/smtpservice.go b/communications/smtpservice/smtpservice.go index 79a46264..7a1fb05b 100644 --- a/communications/smtpservice/smtpservice.go +++ b/communications/smtpservice/smtpservice.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net/smtp" + "strings" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/communications/base" @@ -56,7 +57,7 @@ func (s *SMTPservice) Send(subject, alert string) error { return errors.New("STMPservice Send() please add subject and alert") } - list := common.SplitStrings(s.RecipientList, ",") + list := strings.Split(s.RecipientList, ",") for i := range list { messageToSend := fmt.Sprintf( diff --git a/communications/telegram/telegram.go b/communications/telegram/telegram.go index 8fbdd83a..33f0d19c 100644 --- a/communications/telegram/telegram.go +++ b/communications/telegram/telegram.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net/http" + "strings" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/communications/base" @@ -139,25 +140,25 @@ func (t *Telegram) InitialConnect() { // HandleMessages handles incoming message from the long polling routine func (t *Telegram) HandleMessages(text string, chatID int64) error { switch { - case common.StringContains(text, cmdHelp): + case strings.Contains(text, cmdHelp): return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, cmdHelpReply), chatID) - case common.StringContains(text, cmdStart): + case strings.Contains(text, cmdStart): return t.SendMessage(fmt.Sprintf("%s: START COMMANDS HERE", talkRoot), chatID) - case common.StringContains(text, cmdOrders): + case strings.Contains(text, cmdOrders): return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, t.GetOrderbook("ANX")), chatID) - case common.StringContains(text, cmdStatus): + case strings.Contains(text, cmdStatus): return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, t.GetStatus()), chatID) - case common.StringContains(text, cmdTicker): + case strings.Contains(text, cmdTicker): return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, t.GetTicker("ANX")), chatID) - case common.StringContains(text, cmdSettings): + case strings.Contains(text, cmdSettings): return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, t.GetSettings()), chatID) - case common.StringContains(text, cmdPortfolio): + case strings.Contains(text, cmdPortfolio): return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, t.GetPortfolio()), chatID) default: diff --git a/config/config.go b/config/config.go index dc6f7f23..5c7e60e8 100644 --- a/config/config.go +++ b/config/config.go @@ -47,7 +47,7 @@ const ( // Constants here hold some messages const ( ErrExchangeNameEmpty = "exchange #%d name is empty" - ErrExchangeAvailablePairsEmpty = "exchange %s avaiable pairs is empty" + ErrExchangeAvailablePairsEmpty = "exchange %s available pairs is empty" ErrExchangeEnabledPairsEmpty = "exchange %s enabled pairs is empty" ErrExchangeBaseCurrenciesEmpty = "exchange %s base currencies is empty" ErrExchangeNotFound = "exchange %s not found" @@ -95,7 +95,7 @@ func (c *Config) GetExchangeBankAccounts(exchangeName, depositingCurrency string for x := range c.Exchanges { if strings.EqualFold(c.Exchanges[x].Name, exchangeName) { for y := range c.Exchanges[x].BankAccounts { - if common.StringContains(c.Exchanges[x].BankAccounts[y].SupportedCurrencies, + if strings.Contains(c.Exchanges[x].BankAccounts[y].SupportedCurrencies, depositingCurrency) { return c.Exchanges[x].BankAccounts[y], nil } @@ -130,9 +130,9 @@ func (c *Config) GetClientBankAccounts(exchangeName, targetCurrency string) (Ban defer m.Unlock() for x := range c.BankAccounts { - if (common.StringContains(c.BankAccounts[x].SupportedExchanges, exchangeName) || + if (strings.Contains(c.BankAccounts[x].SupportedExchanges, exchangeName) || c.BankAccounts[x].SupportedExchanges == "ALL") && - common.StringContains(c.BankAccounts[x].SupportedCurrencies, targetCurrency) { + strings.Contains(c.BankAccounts[x].SupportedCurrencies, targetCurrency) { return c.BankAccounts[x], nil } @@ -518,13 +518,13 @@ func (c *Config) CheckPairConfigFormats(exchName string) error { for y := range loadedPairs { if pairFmt.Delimiter != "" { - if !common.StringContains(loadedPairs[y].String(), pairFmt.Delimiter) { + if !strings.Contains(loadedPairs[y].String(), pairFmt.Delimiter) { return fmt.Errorf("exchange %s %s %v pairs does not contain delimiter", exchName, pairsType, assetType) } } if pairFmt.Index != "" { - if !common.StringContains(loadedPairs[y].String(), pairFmt.Index) { + if !strings.Contains(loadedPairs[y].String(), pairFmt.Index) { return fmt.Errorf("exchange %s %s %v pairs does not contain an index", exchName, pairsType, assetType) } } @@ -602,7 +602,8 @@ func (c *Config) CheckPairConsistency(exchName string) error { if err != nil { return fmt.Errorf("exchange %s failed to set pairs: %v", exchName, err) } - log.Warnf("Exchange %s: No enabled pairs found in available pairs, randomly added %v pair.\n", exchName, newPair) + log.Warnf("Exchange %s: [%v] No enabled pairs found in available pairs, randomly added %v pair.\n", + exchName, assetTypes[x], newPair) continue } else { err = c.SetPairs(exchName, assetTypes[x], true, pairs) @@ -610,7 +611,8 @@ func (c *Config) CheckPairConsistency(exchName string) error { return fmt.Errorf("exchange %s failed to set pairs: %v", exchName, err) } } - log.Warnf("Exchange %s: Removing enabled pair(s) %v from enabled pairs as it isn't an available pair.", exchName, pairsRemoved.Strings()) + log.Warnf("Exchange %s: [%v] Removing enabled pair(s) %v from enabled pairs as it isn't an available pair.", + exchName, assetTypes[x], pairsRemoved.Strings()) } return nil } @@ -1326,15 +1328,20 @@ func GetFilePath(file string) (string, error) { return "", err } - oldDir := exePath + common.GetOSPathSlash() - oldDirs := []string{oldDir + ConfigFile, oldDir + EncryptedConfigFile} + oldDirs := []string{ + filepath.Join(exePath, ConfigFile), + filepath.Join(exePath, EncryptedConfigFile), + } - newDir := common.GetDefaultDataDir(runtime.GOOS) + common.GetOSPathSlash() + newDir := common.GetDefaultDataDir(runtime.GOOS) err = common.CreateDir(newDir) if err != nil { return "", err } - newDirs := []string{newDir + ConfigFile, newDir + EncryptedConfigFile} + newDirs := []string{ + filepath.Join(newDir, ConfigFile), + filepath.Join(newDir, EncryptedConfigFile), + } // First upgrade the old dir config file if it exists to the corresponding new one for x := range oldDirs { diff --git a/currency/code.go b/currency/code.go index 2d00e5b3..3dcabdab 100644 --- a/currency/code.go +++ b/currency/code.go @@ -3,6 +3,7 @@ package currency import ( "errors" "fmt" + "strings" "sync" "time" @@ -294,8 +295,8 @@ func (b *BaseCodes) UpdateContract(fullName, symbol, assocExchange string) error // Register registers a currency from a string and returns a currency code func (b *BaseCodes) Register(c string) Code { - NewUpperCode := common.StringToUpper(c) - format := common.StringContains(c, NewUpperCode) + NewUpperCode := strings.ToUpper(c) + format := strings.Contains(c, NewUpperCode) b.mtx.Lock() defer b.mtx.Unlock() @@ -321,7 +322,7 @@ func (b *BaseCodes) Register(c string) Code { // RegisterFiat registers a fiat currency from a string and returns a currency // code func (b *BaseCodes) RegisterFiat(c string) (Code, error) { - c = common.StringToUpper(c) + c = strings.ToUpper(c) b.mtx.Lock() defer b.mtx.Unlock() @@ -427,7 +428,7 @@ func (c Code) String() string { if c.UpperCase { return c.Item.Symbol } - return common.StringToLower(c.Item.Symbol) + return strings.ToLower(c.Item.Symbol) } // Lower converts the code to lowercase formatting diff --git a/currency/code_test.go b/currency/code_test.go index 4d675b85..573461a0 100644 --- a/currency/code_test.go +++ b/currency/code_test.go @@ -8,31 +8,31 @@ import ( func TestRoleString(t *testing.T) { if Unset.String() != UnsetRollString { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", UnsetRollString, Unset) } if Fiat.String() != FiatCurrencyString { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", FiatCurrencyString, Fiat) } if Cryptocurrency.String() != CryptocurrencyString { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", CryptocurrencyString, Cryptocurrency) } if Token.String() != TokenString { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", TokenString, Token) } if Contract.String() != ContractString { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", ContractString, Contract) } @@ -40,7 +40,7 @@ func TestRoleString(t *testing.T) { var random Role = 1 << 7 if random.String() != "UNKNOWN" { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", "UNKNOWN", random) } @@ -54,7 +54,7 @@ func TestRoleMarshalJSON(t *testing.T) { expected := `"fiatCurrency"` if string(d) != expected { - t.Errorf("Test Failed - Role MarshalJSON() error expected %s but recieved %s", + t.Errorf("Test Failed - Role MarshalJSON() error expected %s but received %s", expected, string(d)) } @@ -100,37 +100,37 @@ func TestRoleUnmarshalJSON(t *testing.T) { } if incoming.RoleOne != Unset { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", Unset, incoming.RoleOne) } if incoming.RoleTwo != Cryptocurrency { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", Cryptocurrency, incoming.RoleTwo) } if incoming.RoleThree != Fiat { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", Fiat, incoming.RoleThree) } if incoming.RoleFour != Token { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", Token, incoming.RoleFour) } if incoming.RoleFive != Contract { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", Contract, incoming.RoleFive) } if incoming.RoleUnknown != Unset { - t.Errorf("Test Failed - Role String() error expected %s but recieved %s", + t.Errorf("Test Failed - Role String() error expected %s but received %s", incoming.RoleFive, incoming.RoleUnknown) } @@ -139,35 +139,35 @@ func TestRoleUnmarshalJSON(t *testing.T) { func TestBaseCode(t *testing.T) { var main BaseCodes if main.HasData() { - t.Errorf("Test Failed - BaseCode HasData() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode HasData() error expected false but received %v", main.HasData()) } catsCode := main.Register("CATS") if !main.HasData() { - t.Errorf("Test Failed - BaseCode HasData() error expected true but recieved %v", + t.Errorf("Test Failed - BaseCode HasData() error expected true but received %v", main.HasData()) } if !main.Register("CATS").Match(catsCode) { - t.Errorf("Test Failed - BaseCode Match() error expected true but recieved %v", + t.Errorf("Test Failed - BaseCode Match() error expected true but received %v", false) } if main.Register("DOGS").Match(catsCode) { - t.Errorf("Test Failed - BaseCode Match() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode Match() error expected false but received %v", true) } loadedCurrencies := main.GetCurrencies() if loadedCurrencies.Contains(main.Register("OWLS")) { - t.Errorf("Test Failed - BaseCode Contains() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode Contains() error expected false but received %v", true) } if !loadedCurrencies.Contains(catsCode) { - t.Errorf("Test Failed - BaseCode Contains() error expected true but recieved %v", + t.Errorf("Test Failed - BaseCode Contains() error expected true but received %v", false) } @@ -194,22 +194,22 @@ func TestBaseCode(t *testing.T) { contract := main.Register("XBTUSD") if contract.IsFiatCurrency() { - t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but received %v", true) } if contract.IsCryptocurrency() { - t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but received %v", true) } if contract.IsDefaultFiatCurrency() { - t.Errorf("Test Failed - BaseCode IsDefaultFiatCurrency() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode IsDefaultFiatCurrency() error expected false but received %v", true) } if contract.IsDefaultFiatCurrency() { - t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but recieved %v", + t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but received %v", true) } @@ -229,32 +229,32 @@ func TestBaseCode(t *testing.T) { } if len(full.Contracts) != 1 { - t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but recieved %v", + t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.Contracts)) } if len(full.Cryptocurrency) != 2 { - t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but recieved %v", + t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.Cryptocurrency)) } if len(full.FiatCurrency) != 1 { - t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but recieved %v", + t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.FiatCurrency)) } if len(full.Token) != 1 { - t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but recieved %v", + t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v", len(full.Token)) } if len(full.UnsetCurrency) != 3 { - t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 3 but recieved %v", + t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 3 but received %v", len(full.UnsetCurrency)) } if !full.LastMainUpdate.IsZero() { - t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 0 but recieved %s", + t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 0 but received %s", full.LastMainUpdate) } } @@ -263,7 +263,7 @@ func TestCodeString(t *testing.T) { expected := "TEST" cc := NewCode("TEST") if cc.String() != expected { - t.Errorf("Test Failed - Currency Code String() error expected %s but recieved %s", + t.Errorf("Test Failed - Currency Code String() error expected %s but received %s", expected, cc) } } @@ -272,7 +272,7 @@ func TestCodeLower(t *testing.T) { expected := "test" cc := NewCode("TEST") if cc.Lower().String() != expected { - t.Errorf("Test Failed - Currency Code Lower() error expected %s but recieved %s", + t.Errorf("Test Failed - Currency Code Lower() error expected %s but received %s", expected, cc.Lower()) } @@ -282,7 +282,7 @@ func TestCodeUpper(t *testing.T) { expected := "TEST" cc := NewCode("test") if cc.Upper().String() != expected { - t.Errorf("Test Failed - Currency Code Upper() error expected %s but recieved %s", + t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s", expected, cc.Upper()) } @@ -307,7 +307,7 @@ func TestCodeUnmarshalJSON(t *testing.T) { } if unmarshalHere.String() != expected { - t.Errorf("Test Failed - Currency Code Upper() error expected %s but recieved %s", + t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s", expected, unmarshalHere) } @@ -328,7 +328,7 @@ func TestCodeMarshalJSON(t *testing.T) { } if string(encoded) != expectedJSON { - t.Errorf("Test Failed - Currency Code Upper() error expected %s but recieved %s", + t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s", expectedJSON, string(encoded)) } @@ -346,7 +346,7 @@ func TestCodeMarshalJSON(t *testing.T) { newExpectedJSON := `{"sweetCodes":""}` if string(encoded) != newExpectedJSON { - t.Errorf("Test Failed - Currency Code Upper() error expected %s but recieved %s", + t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s", newExpectedJSON, string(encoded)) } } @@ -419,7 +419,7 @@ func TestItemString(t *testing.T) { } if newItem.String() != expected { - t.Errorf("Test Failed - Item String() error expected %s but recieved %s", + t.Errorf("Test Failed - Item String() error expected %s but received %s", expected, &newItem) } diff --git a/currency/conversion_test.go b/currency/conversion_test.go index a2cbf08c..da61200b 100644 --- a/currency/conversion_test.go +++ b/currency/conversion_test.go @@ -1,9 +1,8 @@ package currency import ( + "strings" "testing" - - "github.com/thrasher-/gocryptotrader/common" ) func TestNewConversionFromString(t *testing.T) { @@ -18,7 +17,7 @@ func TestNewConversionFromString(t *testing.T) { conv) } - newexpected := common.StringToLower(expected) + newexpected := strings.ToLower(expected) conv, err = NewConversionFromString(newexpected) if err != nil { t.Error("Test Failed - NewConversionFromString() error", err) @@ -110,7 +109,7 @@ func TestConversionsRatesSystem(t *testing.T) { var SuperDuperConversionSystem ConversionRates if SuperDuperConversionSystem.HasData() { - t.Fatalf("Test Failed - HasData() error expected false but recieved %v", + t.Fatalf("Test Failed - HasData() error expected false but received %v", SuperDuperConversionSystem.HasData()) } @@ -151,7 +150,7 @@ func TestConversionsRatesSystem(t *testing.T) { } if !SuperDuperConversionSystem.HasData() { - t.Fatalf("Test Failed - HasData() error expected true but recieved %v", + t.Fatalf("Test Failed - HasData() error expected true but received %v", SuperDuperConversionSystem.HasData()) } @@ -162,7 +161,7 @@ func TestConversionsRatesSystem(t *testing.T) { r := *p * 1000 expectedRate := 1396.9317581 if r != expectedRate { - t.Errorf("Test Failed - Convert() error expected %.13f but recieved %.13f", + t.Errorf("Test Failed - Convert() error expected %.13f but received %.13f", expectedRate, r) } @@ -170,7 +169,7 @@ func TestConversionsRatesSystem(t *testing.T) { inverseR := *pi * expectedRate expectedInverseRate := float64(1000) if inverseR != expectedInverseRate { - t.Errorf("Test Failed - Convert() error expected %.13f but recieved %.13f", + t.Errorf("Test Failed - Convert() error expected %.13f but received %.13f", expectedInverseRate, inverseR) } diff --git a/currency/currencies.go b/currency/currencies.go index 853aabd4..db96fa4e 100644 --- a/currency/currencies.go +++ b/currency/currencies.go @@ -1,6 +1,10 @@ package currency -import "github.com/thrasher-/gocryptotrader/common" +import ( + "strings" + + "github.com/thrasher-/gocryptotrader/common" +) // NewCurrenciesFromStringArray returns a Currencies object from strings func NewCurrenciesFromStringArray(currencies []string) Currencies { @@ -38,7 +42,7 @@ func (c Currencies) Contains(cc Code) bool { // Join returns a comma serparated string func (c Currencies) Join() string { - return common.JoinStrings(c.Strings(), ",") + return strings.Join(c.Strings(), ",") } // UnmarshalJSON comforms type to the umarshaler interface @@ -50,7 +54,7 @@ func (c *Currencies) UnmarshalJSON(d []byte) error { } var allTheCurrencies Currencies - for _, data := range common.SplitStrings(configCurrencies, ",") { + for _, data := range strings.Split(configCurrencies, ",") { allTheCurrencies = append(allTheCurrencies, NewCode(data)) } diff --git a/currency/currency_test.go b/currency/currency_test.go index 20008769..f6e3dae7 100644 --- a/currency/currency_test.go +++ b/currency/currency_test.go @@ -44,14 +44,14 @@ func TestUpdateBaseCurrency(t *testing.T) { } if GetBaseCurrency() != AUD { - t.Errorf("Test failed - GetBaseCurrency() expected %s but recieved %s", + t.Errorf("Test failed - GetBaseCurrency() expected %s but received %s", AUD, GetBaseCurrency()) } } func TestGetDefaultBaseCurrency(t *testing.T) { if GetDefaultBaseCurrency() != USD { - t.Errorf("Test failed - GetDefaultBaseCurrency() expected %s but recieved %s", + t.Errorf("Test failed - GetDefaultBaseCurrency() expected %s but received %s", USD, GetDefaultBaseCurrency()) } } @@ -59,7 +59,7 @@ func TestGetDefaultBaseCurrency(t *testing.T) { func TestGetDefaulCryptoCurrencies(t *testing.T) { expected := Currencies{BTC, LTC, ETH, DOGE, DASH, XRP, XMR} if !GetDefaultCryptocurrencies().Match(expected) { - t.Errorf("Test failed - GetDefaultCryptocurrencies() expected %s but recieved %s", + t.Errorf("Test failed - GetDefaultCryptocurrencies() expected %s but received %s", expected, GetDefaultCryptocurrencies()) } } @@ -67,7 +67,7 @@ func TestGetDefaulCryptoCurrencies(t *testing.T) { func TestGetDefaultFiatCurrencies(t *testing.T) { expected := Currencies{USD, AUD, EUR, CNY} if !GetDefaultFiatCurrencies().Match(expected) { - t.Errorf("Test failed - GetDefaultFiatCurrencies() expected %s but recieved %s", + t.Errorf("Test failed - GetDefaultFiatCurrencies() expected %s but received %s", expected, GetDefaultFiatCurrencies()) } } diff --git a/currency/forexprovider/base/base_interface.go b/currency/forexprovider/base/base_interface.go index 5e360833..dabdf01a 100644 --- a/currency/forexprovider/base/base_interface.go +++ b/currency/forexprovider/base/base_interface.go @@ -3,6 +3,7 @@ package base import ( "errors" "fmt" + "strings" "sync" "github.com/thrasher-/gocryptotrader/common" @@ -49,7 +50,7 @@ func (p *Provider) GetNewRate(base string, currencies []string) (map[string]floa return p.Provider.GetRates(base, "") // Zero value to get all rates default: - return p.Provider.GetRates(base, common.JoinStrings(currencies, ",")) + return p.Provider.GetRates(base, strings.Join(currencies, ",")) } } diff --git a/currency/forexprovider/currencyconverterapi/currencyconverterapi.go b/currency/forexprovider/currencyconverterapi/currencyconverterapi.go index 5c23ebd7..d63082db 100644 --- a/currency/forexprovider/currencyconverterapi/currencyconverterapi.go +++ b/currency/forexprovider/currencyconverterapi/currencyconverterapi.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/url" + "strings" "time" "github.com/thrasher-/gocryptotrader/common" @@ -54,7 +55,7 @@ func (c *CurrencyConverter) Setup(config base.Settings) error { // GetRates is a wrapper function to return rates func (c *CurrencyConverter) GetRates(baseCurrency, symbols string) (map[string]float64, error) { - splitSymbols := common.SplitStrings(symbols, ",") + splitSymbols := strings.Split(symbols, ",") if len(splitSymbols) == 1 { return c.Convert(baseCurrency, symbols) @@ -79,7 +80,7 @@ func (c *CurrencyConverter) GetRates(baseCurrency, symbols string) (map[string]f continue } for k, v := range result { - rates[common.ReplaceString(k, "_", "", -1)] = v + rates[strings.Replace(k, "_", "", -1)] = v } } } @@ -98,7 +99,7 @@ func (c *CurrencyConverter) GetRates(baseCurrency, symbols string) (map[string]f } for k, v := range result { - rates[common.ReplaceString(k, "_", "", -1)] = v + rates[strings.Replace(k, "_", "", -1)] = v } return rates, nil @@ -113,7 +114,7 @@ func (c *CurrencyConverter) ConvertMany(currencies []string) (map[string]float64 result := make(map[string]float64) v := url.Values{} - joined := common.JoinStrings(currencies, ",") + joined := strings.Join(currencies, ",") v.Set("q", joined) v.Set("compact", "ultra") diff --git a/currency/forexprovider/currencylayer/currencylayer.go b/currency/forexprovider/currencylayer/currencylayer.go index 7b9d9345..45f33592 100644 --- a/currency/forexprovider/currencylayer/currencylayer.go +++ b/currency/forexprovider/currencylayer/currencylayer.go @@ -17,6 +17,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/thrasher-/gocryptotrader/common" @@ -125,7 +126,7 @@ func (c *CurrencyLayer) GetliveData(currencies, source string) (map[string]float func (c *CurrencyLayer) GetHistoricalData(date string, currencies []string, source string) (map[string]float64, error) { var resp HistoricalRates v := url.Values{} - v.Set("currencies", common.JoinStrings(currencies, ",")) + v.Set("currencies", strings.Join(currencies, ",")) v.Set("source", source) v.Set("date", date) @@ -179,7 +180,7 @@ func (c *CurrencyLayer) QueryTimeFrame(startDate, endDate, baseCurrency string, v.Set("start_date", startDate) v.Set("end_date", endDate) v.Set("base", baseCurrency) - v.Set("currencies", common.JoinStrings(currencies, ",")) + v.Set("currencies", strings.Join(currencies, ",")) err := c.SendHTTPRequest(APIEndpointTimeframe, v, &resp) if err != nil { @@ -205,7 +206,7 @@ func (c *CurrencyLayer) QueryCurrencyChange(startDate, endDate, baseCurrency str v.Set("start_date", startDate) v.Set("end_date", endDate) v.Set("base", baseCurrency) - v.Set("currencies", common.JoinStrings(currencies, ",")) + v.Set("currencies", strings.Join(currencies, ",")) err := c.SendHTTPRequest(APIEndpointChange, v, &resp) if err != nil { diff --git a/currency/forexprovider/exchangeratesapi.io/exchangeratesapi.go b/currency/forexprovider/exchangeratesapi.io/exchangeratesapi.go index 2b58bc79..25326139 100644 --- a/currency/forexprovider/exchangeratesapi.io/exchangeratesapi.go +++ b/currency/forexprovider/exchangeratesapi.io/exchangeratesapi.go @@ -66,7 +66,7 @@ func cleanCurrencies(baseCurrency, symbols string) string { } // remove and warn about any unsupported currencies - if !common.StringContains(exchangeRatesSupportedCurrencies, x) { + if !strings.Contains(exchangeRatesSupportedCurrencies, x) { log.Warnf("Forex provider ExchangeRatesAPI does not support currency %s, removing from forex rates query.", x) continue } @@ -164,7 +164,7 @@ func (e *ExchangeRates) GetRates(baseCurrency, symbols string) (map[string]float // GetSupportedCurrencies returns the supported currency list func (e *ExchangeRates) GetSupportedCurrencies() ([]string, error) { - return common.SplitStrings(exchangeRatesSupportedCurrencies, ","), nil + return strings.Split(exchangeRatesSupportedCurrencies, ","), nil } // SendHTTPRequest sends a HTTPS request to the desired endpoint and returns the result diff --git a/currency/forexprovider/fixer.io/fixer.go b/currency/forexprovider/fixer.io/fixer.go index d83642ae..85848cce 100644 --- a/currency/forexprovider/fixer.io/fixer.go +++ b/currency/forexprovider/fixer.io/fixer.go @@ -13,6 +13,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/thrasher-/gocryptotrader/common" @@ -142,7 +143,7 @@ func (f *Fixer) GetHistoricalRates(date, baseCurrency string, symbols []string) var resp Rates v := url.Values{} - v.Set("symbols", common.JoinStrings(symbols, ",")) + v.Set("symbols", strings.Join(symbols, ",")) if baseCurrency != "" { v.Set("base", baseCurrency) @@ -205,7 +206,7 @@ func (f *Fixer) GetTimeSeriesData(startDate, endDate, baseCurrency string, symbo v.Set("start_date", startDate) v.Set("end_date", endDate) v.Set("base", baseCurrency) - v.Set("symbols", common.JoinStrings(symbols, ",")) + v.Set("symbols", strings.Join(symbols, ",")) err := f.SendOpenHTTPRequest(fixerAPITimeSeries, v, &resp) if err != nil { @@ -231,7 +232,7 @@ func (f *Fixer) GetFluctuationData(startDate, endDate, baseCurrency string, symb v.Set("start_date", startDate) v.Set("end_date", endDate) v.Set("base", baseCurrency) - v.Set("symbols", common.JoinStrings(symbols, ",")) + v.Set("symbols", strings.Join(symbols, ",")) err := f.SendOpenHTTPRequest(fixerAPIFluctuation, v, &resp) if err != nil { diff --git a/currency/forexprovider/openexchangerates/openexchangerates.go b/currency/forexprovider/openexchangerates/openexchangerates.go index 9c00b676..6ac7cfcf 100644 --- a/currency/forexprovider/openexchangerates/openexchangerates.go +++ b/currency/forexprovider/openexchangerates/openexchangerates.go @@ -14,6 +14,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/thrasher-/gocryptotrader/common" @@ -126,7 +127,7 @@ func (o *OXR) GetHistoricalRates(date, baseCurrency string, symbols []string, pr v := url.Values{} v.Set("base", baseCurrency) - v.Set("symbols", common.JoinStrings(symbols, ",")) + v.Set("symbols", strings.Join(symbols, ",")) v.Set("prettyprint", strconv.FormatBool(prettyPrint)) v.Set("show_alternative", strconv.FormatBool(showAlternative)) endpoint := fmt.Sprintf(APIEndpointHistorical, date) @@ -156,7 +157,7 @@ func (o *OXR) GetCurrencies(showInactive, prettyPrint, showAlternative bool) (ma // GetSupportedCurrencies returns a list of supported currencies func (o *OXR) GetSupportedCurrencies() ([]string, error) { - return common.SplitStrings(oxrSupportedCurrencies, ","), nil + return strings.Split(oxrSupportedCurrencies, ","), nil } // GetTimeSeries returns historical exchange rates for a given time period, @@ -172,7 +173,7 @@ func (o *OXR) GetTimeSeries(baseCurrency, startDate, endDate string, symbols []s v.Set("base", baseCurrency) v.Set("start", startDate) v.Set("end", endDate) - v.Set("symbols", common.JoinStrings(symbols, ",")) + v.Set("symbols", strings.Join(symbols, ",")) v.Set("prettyprint", strconv.FormatBool(prettyPrint)) v.Set("show_alternative", strconv.FormatBool(showAlternative)) @@ -220,7 +221,7 @@ func (o *OXR) GetOHLC(startTime, period, baseCurrency string, symbols []string, v.Set("start_time", startTime) v.Set("period", period) v.Set("base", baseCurrency) - v.Set("symbols", common.JoinStrings(symbols, ",")) + v.Set("symbols", strings.Join(symbols, ",")) v.Set("prettyprint", strconv.FormatBool(prettyPrint)) if err := o.SendHTTPRequest(APIEndpointOHLC, v, &resp); err != nil { diff --git a/currency/pairs.go b/currency/pairs.go index 53c468a6..c6882e66 100644 --- a/currency/pairs.go +++ b/currency/pairs.go @@ -2,6 +2,7 @@ package currency import ( "math/rand" + "strings" "github.com/thrasher-/gocryptotrader/common" log "github.com/thrasher-/gocryptotrader/logger" @@ -35,7 +36,7 @@ func (p Pairs) Strings() []string { // Join returns a comma separated list of currency pairs func (p Pairs) Join() string { - return common.JoinStrings(p.Strings(), ",") + return strings.Join(p.Strings(), ",") } // Format formats the pair list to the exchange format configuration @@ -75,7 +76,7 @@ func (p *Pairs) UnmarshalJSON(d []byte) error { } var allThePairs Pairs - for _, data := range common.SplitStrings(pairs, ",") { + for _, data := range strings.Split(pairs, ",") { allThePairs = append(allThePairs, NewPairFromString(data)) } diff --git a/currency/storage.go b/currency/storage.go index 39a567c3..57f75468 100644 --- a/currency/storage.go +++ b/currency/storage.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "path/filepath" "sync" "time" @@ -19,6 +20,7 @@ import ( const ( DefaultCurrencyFileDelay = 168 * time.Hour DefaultForeignExchangeDelay = 1 * time.Minute + DefaultStorageFile = "currency.json" ) func init() { @@ -132,7 +134,7 @@ func (s *Storage) RunUpdater(overrides BotOverrides, settings *MainConfiguration return errors.New("currency package runUpdater error filepath not set") } - s.path = filePath + common.GetOSPathSlash() + "currency.json" + s.path = filepath.Join(filePath, DefaultStorageFile) if settings.CurrencyDelay.Nanoseconds() == 0 { s.currencyFileUpdateDelay = DefaultCurrencyFileDelay diff --git a/engine/events/events.go b/engine/events/events.go index 12807b9e..f5f37400 100644 --- a/engine/events/events.go +++ b/engine/events/events.go @@ -3,9 +3,9 @@ package events import ( "errors" "fmt" + "strings" "time" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/communications" "github.com/thrasher-/gocryptotrader/communications/base" "github.com/thrasher-/gocryptotrader/config" @@ -134,8 +134,8 @@ func GetEventCounter() (total, executed int) { // ExecuteAction will execute the action pending on the chain func (e *Event) ExecuteAction() bool { - if common.StringContains(e.Action, ",") { - action := common.SplitStrings(e.Action, ",") + if strings.Contains(e.Action, ",") { + action := strings.Split(e.Action, ",") if action[0] == ActionSMSNotify { message := fmt.Sprintf("Event triggered: %s", e.String()) if action[1] == "ALL" { @@ -251,9 +251,9 @@ func (e *Event) CheckCondition() bool { // IsValidEvent checks the actions to be taken and returns an error if incorrect func IsValidEvent(exchange, item string, condition ConditionParams, action string) error { - exchange = common.StringToUpper(exchange) - item = common.StringToUpper(item) - action = common.StringToUpper(action) + exchange = strings.ToUpper(exchange) + item = strings.ToUpper(item) + action = strings.ToUpper(action) if !IsValidExchange(exchange) { return errExchangeDisabled @@ -279,8 +279,8 @@ func IsValidEvent(exchange, item string, condition ConditionParams, action strin } } - if common.StringContains(action, ",") { - a := common.SplitStrings(action, ",") + if strings.Contains(action, ",") { + a := strings.Split(action, ",") if a[0] != ActionSMSNotify { return errInvalidAction @@ -326,10 +326,10 @@ func EventManger() { // IsValidExchange validates the exchange func IsValidExchange(exchangeName string) bool { - exchangeName = common.StringToLower(exchangeName) + exchangeName = strings.ToLower(exchangeName) cfg := config.GetConfig() for x := range cfg.Exchanges { - if common.StringToLower(cfg.Exchanges[x].Name) == exchangeName && cfg.Exchanges[x].Enabled { + if strings.ToLower(cfg.Exchanges[x].Name) == exchangeName && cfg.Exchanges[x].Enabled { return true } } @@ -347,7 +347,7 @@ func IsValidCondition(condition string) bool { // IsValidAction validates passed in action func IsValidAction(action string) bool { - action = common.StringToUpper(action) + action = strings.ToUpper(action) switch action { case ActionSMSNotify, ActionConsolePrint, ActionTest: return true @@ -357,7 +357,7 @@ func IsValidAction(action string) bool { // IsValidItem validates passed in Item func IsValidItem(item string) bool { - item = common.StringToUpper(item) + item = strings.ToUpper(item) switch item { case ItemPrice, ItemOrderbook: return true diff --git a/engine/exchange.go b/engine/exchange.go index db4bbacd..55d66781 100644 --- a/engine/exchange.go +++ b/engine/exchange.go @@ -121,7 +121,7 @@ func UnloadExchange(name string) error { // LoadExchange loads an exchange by name func LoadExchange(name string, useWG bool, wg *sync.WaitGroup) error { - nameLower := common.StringToLower(name) + nameLower := strings.ToLower(name) var exch exchange.IBotExchange if len(Bot.Exchanges) > 0 { diff --git a/engine/restful_router.go b/engine/restful_router.go index 4c7048a6..3e988597 100644 --- a/engine/restful_router.go +++ b/engine/restful_router.go @@ -5,6 +5,7 @@ import ( "net/http" _ "net/http/pprof" // blank import required for pprof "strconv" + "strings" "time" "github.com/gorilla/mux" @@ -64,7 +65,7 @@ func newRouter(isREST bool) *mux.Router { if common.ExtractPort(listenAddr) == 80 { listenAddr = common.ExtractHost(listenAddr) } else { - listenAddr = common.JoinStrings([]string{common.ExtractHost(listenAddr), + listenAddr = strings.Join([]string{common.ExtractHost(listenAddr), strconv.Itoa(common.ExtractPort(listenAddr))}, ":") } diff --git a/engine/routines.go b/engine/routines.go index 4c1b4c76..c050a647 100644 --- a/engine/routines.go +++ b/engine/routines.go @@ -3,6 +3,7 @@ package engine import ( "errors" "fmt" + "strings" "sync" "time" @@ -398,7 +399,7 @@ func WebsocketDataHandler(ws *exchange.Websocket) { case error: switch { - case common.StringContains(d.Error(), "close 1006"): + case strings.Contains(d.Error(), "close 1006"): go ws.WebsocketReset() continue default: diff --git a/engine/rpcserver.go b/engine/rpcserver.go index 216bf673..a20e7671 100644 --- a/engine/rpcserver.go +++ b/engine/rpcserver.go @@ -7,6 +7,7 @@ import ( "net" "net/http" "path/filepath" + "strings" "time" grpcauth "github.com/grpc-ecosystem/go-grpc-middleware/auth" @@ -41,17 +42,17 @@ func authenticateClient(ctx context.Context) (context.Context, error) { return ctx, fmt.Errorf("authorization header missing") } - if !common.StringContains(authStr[0], "Basic") { + if !strings.Contains(authStr[0], "Basic") { return ctx, fmt.Errorf("basic not found in authorization header") } - decoded, err := crypto.Base64Decode(common.SplitStrings(authStr[0], " ")[1]) + decoded, err := crypto.Base64Decode(strings.Split(authStr[0], " ")[1]) if err != nil { return ctx, fmt.Errorf("unable to base64 decode authorization header") } - username := common.SplitStrings(string(decoded), ":")[0] - password := common.SplitStrings(string(decoded), ":")[1] + username := strings.Split(string(decoded), ":")[0] + password := strings.Split(string(decoded), ":")[1] if username != Bot.Config.RemoteControl.Username || password != Bot.Config.RemoteControl.Password { return ctx, fmt.Errorf("username/password mismatch") @@ -159,7 +160,7 @@ func (s *RPCServer) GetInfo(ctx context.Context, r *gctrpc.GetInfoRequest) (*gct // GetExchanges returns a list of exchanges // Param is whether or not you wish to list enabled exchanges func (s *RPCServer) GetExchanges(ctx context.Context, r *gctrpc.GetExchangesRequest) (*gctrpc.GetExchangesResponse, error) { - exchanges := common.JoinStrings(GetExchanges(r.Enabled), ",") + exchanges := strings.Join(GetExchanges(r.Enabled), ",") return &gctrpc.GetExchangesResponse{Exchanges: exchanges}, nil } @@ -190,13 +191,13 @@ func (s *RPCServer) GetExchangeInfo(ctx context.Context, r *gctrpc.GenericExchan HttpTimeout: exchCfg.HTTPTimeout.String(), HttpUseragent: exchCfg.HTTPUserAgent, HttpProxy: exchCfg.ProxyAddress, - BaseCurrencies: common.JoinStrings(exchCfg.BaseCurrencies.Strings(), ","), + BaseCurrencies: strings.Join(exchCfg.BaseCurrencies.Strings(), ","), SupportedAssets: exchCfg.CurrencyPairs.AssetTypes.JoinToString(","), // TO-DO fix pairs - //EnabledPairs: common.JoinStrings( + //EnabledPairs: strings.Join( // exchCfg.CurrencyPairs.Pairs.GetPairs().Enabled.Strings(), ","), - //AvailablePairs: common.JoinStrings( + //AvailablePairs: strings.Join( // exchCfg.CurrencyPairs.Spot.Available.Strings(), ","), }, nil } diff --git a/engine/websocket.go b/engine/websocket.go index 6adbbda4..bcb8016e 100644 --- a/engine/websocket.go +++ b/engine/websocket.go @@ -3,6 +3,7 @@ package engine import ( "errors" "net/http" + "strings" "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" @@ -122,7 +123,7 @@ func (c *WebsocketClient) read() { break } - req := common.StringToLower(evt.Event) + req := strings.ToLower(evt.Event) log.Debugf("websocket: request received: %s", req) result, ok := wsHandlers[req] diff --git a/exchanges/alphapoint/alphapoint.go b/exchanges/alphapoint/alphapoint.go index 15d7a650..c32e2213 100644 --- a/exchanges/alphapoint/alphapoint.go +++ b/exchanges/alphapoint/alphapoint.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strconv" + "strings" "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" @@ -534,7 +535,7 @@ func (a *Alphapoint) SendAuthenticatedHTTPRequest(method, path string, data map[ hmac := crypto.GetHMAC(crypto.HashSHA256, []byte(n.String()+a.API.Credentials.ClientID+a.API.Credentials.Key), []byte(a.API.Credentials.Secret)) - data["apiSig"] = common.StringToUpper(crypto.HexEncodeToString(hmac)) + data["apiSig"] = strings.ToUpper(crypto.HexEncodeToString(hmac)) path = fmt.Sprintf("%s/ajax/v%s/%s", a.API.Endpoints.URL, alphapointAPIVersion, path) PayloadJSON, err := common.JSONEncode(data) diff --git a/exchanges/assets/assets.go b/exchanges/assets/assets.go index ea95eac8..57e50ba3 100644 --- a/exchanges/assets/assets.go +++ b/exchanges/assets/assets.go @@ -2,8 +2,6 @@ package assets import ( "strings" - - "github.com/thrasher-/gocryptotrader/common" ) // AssetType stores the asset type @@ -93,7 +91,7 @@ func IsValid(input AssetType) bool { // New takes an input of asset types as string and returns an AssetTypes // array func New(input string) AssetTypes { - if !common.StringContains(input, ",") { + if !strings.Contains(input, ",") { if IsValid(AssetType(input)) { return AssetTypes{ AssetType(input), diff --git a/exchanges/binance/binance.go b/exchanges/binance/binance.go index 0d5a05e6..93fb514d 100644 --- a/exchanges/binance/binance.go +++ b/exchanges/binance/binance.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/gorilla/websocket" @@ -92,7 +93,7 @@ func (b *Binance) GetOrderBook(obd OrderBookDataRequestParams) (OrderBook, error } params := url.Values{} - params.Set("symbol", common.StringToUpper(obd.Symbol)) + params.Set("symbol", strings.ToUpper(obd.Symbol)) params.Set("limit", fmt.Sprintf("%d", obd.Limit)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, orderBookDepth, params.Encode()) @@ -143,7 +144,7 @@ func (b *Binance) GetRecentTrades(rtr RecentTradeRequestParams) ([]RecentTrade, var resp []RecentTrade params := url.Values{} - params.Set("symbol", common.StringToUpper(rtr.Symbol)) + params.Set("symbol", strings.ToUpper(rtr.Symbol)) params.Set("limit", fmt.Sprintf("%d", rtr.Limit)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, recentTrades, params.Encode()) @@ -164,7 +165,7 @@ func (b *Binance) GetHistoricalTrades(symbol string, limit int, fromID int64) ([ } params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) params.Set("limit", strconv.Itoa(limit)) params.Set("fromid", strconv.FormatInt(fromID, 10)) @@ -185,7 +186,7 @@ func (b *Binance) GetAggregatedTrades(symbol string, limit int) ([]AggregatedTra } params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) params.Set("limit", strconv.Itoa(limit)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, aggregatedTrades, params.Encode()) @@ -263,7 +264,7 @@ func (b *Binance) GetSpotKline(arg KlinesRequestParams) ([]CandleStick, error) { func (b *Binance) GetAveragePrice(symbol string) (AveragePrice, error) { resp := AveragePrice{} params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, averagePrice, params.Encode()) @@ -276,7 +277,7 @@ func (b *Binance) GetAveragePrice(symbol string) (AveragePrice, error) { func (b *Binance) GetPriceChangeStats(symbol string) (PriceChangeStats, error) { resp := PriceChangeStats{} params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, priceChange, params.Encode()) @@ -296,7 +297,7 @@ func (b *Binance) GetTickers() ([]PriceChangeStats, error) { func (b *Binance) GetLatestSpotPrice(symbol string) (SymbolPrice, error) { resp := SymbolPrice{} params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, symbolPrice, params.Encode()) @@ -309,7 +310,7 @@ func (b *Binance) GetLatestSpotPrice(symbol string) (SymbolPrice, error) { func (b *Binance) GetBestPrice(symbol string) (BestPrice, error) { resp := BestPrice{} params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) path := fmt.Sprintf("%s%s?%s", b.API.Endpoints.URL, bestPrice, params.Encode()) @@ -391,7 +392,7 @@ func (b *Binance) OpenOrders(symbol string) ([]QueryOrderData, error) { params := url.Values{} if symbol != "" { - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) } if err := b.SendAuthHTTPRequest(http.MethodGet, path, params, &resp); err != nil { @@ -410,7 +411,7 @@ func (b *Binance) AllOrders(symbol, orderID, limit string) ([]QueryOrderData, er path := fmt.Sprintf("%s%s", b.API.Endpoints.URL, allOrders) params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) if orderID != "" { params.Set("orderId", orderID) } @@ -431,7 +432,7 @@ func (b *Binance) QueryOrder(symbol, origClientOrderID string, orderID int64) (Q path := fmt.Sprintf("%s%s", b.API.Endpoints.URL, queryOrder) params := url.Values{} - params.Set("symbol", common.StringToUpper(symbol)) + params.Set("symbol", strings.ToUpper(symbol)) if origClientOrderID != "" { params.Set("origClientOrderId", origClientOrderID) } diff --git a/exchanges/bitfinex/bitfinex_wrapper.go b/exchanges/bitfinex/bitfinex_wrapper.go index 07d9b81c..e4424615 100644 --- a/exchanges/bitfinex/bitfinex_wrapper.go +++ b/exchanges/bitfinex/bitfinex_wrapper.go @@ -170,7 +170,7 @@ func (b *Bitfinex) UpdateTicker(p currency.Pair, assetType assets.AssetType) (ti pairs = append(pairs, "t"+enabledPairs[x].String()) } - tickerNew, err := b.GetTickersV2(common.JoinStrings(pairs, ",")) + tickerNew, err := b.GetTickersV2(strings.Join(pairs, ",")) if err != nil { return tickerPrice, err } diff --git a/exchanges/bitflyer/bitflyer_wrapper.go b/exchanges/bitflyer/bitflyer_wrapper.go index 21f3be5c..97a2339f 100644 --- a/exchanges/bitflyer/bitflyer_wrapper.go +++ b/exchanges/bitflyer/bitflyer_wrapper.go @@ -2,6 +2,7 @@ package bitflyer import ( "errors" + "strings" "sync" "time" @@ -136,7 +137,7 @@ func (b *Bitflyer) FetchTradablePairs(assetType assets.AssetType) ([]string, err for _, info := range pairs { if info.Alias != "" && assetType == assets.AssetTypeFutures { products = append(products, info.Alias) - } else if info.Alias == "" && assetType == assets.AssetTypeSpot && common.StringContains(info.ProductCode, "_") { + } else if info.Alias == "" && assetType == assets.AssetTypeSpot && strings.Contains(info.ProductCode, "_") { products = append(products, info.ProductCode) } } @@ -198,7 +199,7 @@ func (b *Bitflyer) FetchTicker(p currency.Pair, assetType assets.AssetType) (tic // CheckFXString upgrades currency pair if needed func (b *Bitflyer) CheckFXString(p currency.Pair) currency.Pair { - if common.StringContains(p.Base.String(), "FX") { + if strings.Contains(p.Base.String(), "FX") { p.Base = currency.FX_BTC return p } diff --git a/exchanges/bithumb/bithumb.go b/exchanges/bithumb/bithumb.go index 63d19651..4c7d9515 100644 --- a/exchanges/bithumb/bithumb.go +++ b/exchanges/bithumb/bithumb.go @@ -9,6 +9,7 @@ import ( "net/url" "reflect" "strconv" + "strings" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/common/crypto" @@ -74,7 +75,7 @@ func (b *Bithumb) GetTradablePairs() ([]string, error) { // symbol e.g. "btc" func (b *Bithumb) GetTicker(symbol string) (Ticker, error) { response := Ticker{} - path := fmt.Sprintf("%s%s%s", b.API.Endpoints.URL, publicTicker, common.StringToUpper(symbol)) + path := fmt.Sprintf("%s%s%s", b.API.Endpoints.URL, publicTicker, strings.ToUpper(symbol)) err := b.SendHTTPRequest(path, &response) if err != nil { @@ -140,7 +141,7 @@ func (b *Bithumb) GetAllTickers() (map[string]Ticker, error) { // symbol e.g. "btc" func (b *Bithumb) GetOrderBook(symbol string) (Orderbook, error) { response := Orderbook{} - path := fmt.Sprintf("%s%s%s", b.API.Endpoints.URL, publicOrderBook, common.StringToUpper(symbol)) + path := fmt.Sprintf("%s%s%s", b.API.Endpoints.URL, publicOrderBook, strings.ToUpper(symbol)) err := b.SendHTTPRequest(path, &response) if err != nil { @@ -159,7 +160,7 @@ func (b *Bithumb) GetOrderBook(symbol string) (Orderbook, error) { // symbol e.g. "btc" func (b *Bithumb) GetTransactionHistory(symbol string) (TransactionHistory, error) { response := TransactionHistory{} - path := fmt.Sprintf("%s%s%s", b.API.Endpoints.URL, publicTransactionHistory, common.StringToUpper(symbol)) + path := fmt.Sprintf("%s%s%s", b.API.Endpoints.URL, publicTransactionHistory, strings.ToUpper(symbol)) err := b.SendHTTPRequest(path, &response) if err != nil { @@ -210,7 +211,7 @@ func (b *Bithumb) GetAccountBalance(c string) (FullBalance, error) { // Added due to increasing of the usuable currencies on exchange, usually // without notificatation, so we dont need to update structs later on for tag, datum := range response.Data { - splitTag := common.SplitStrings(tag, "_") + splitTag := strings.Split(tag, "_") c := splitTag[len(splitTag)-1] var val float64 if reflect.TypeOf(datum).String() != "float64" { @@ -253,7 +254,7 @@ func (b *Bithumb) GetAccountBalance(c string) (FullBalance, error) { func (b *Bithumb) GetWalletAddress(currency string) (WalletAddressRes, error) { response := WalletAddressRes{} params := url.Values{} - params.Set("currency", common.StringToUpper(currency)) + params.Set("currency", strings.ToUpper(currency)) err := b.SendAuthenticatedHTTPRequest(privateWalletAdd, params, &response) if err != nil { @@ -305,7 +306,7 @@ func (b *Bithumb) GetOrders(orderID, transactionType, count, after, currency str } if len(currency) > 0 { - params.Set("currency", common.StringToUpper(currency)) + params.Set("currency", strings.ToUpper(currency)) } return response, @@ -331,9 +332,9 @@ func (b *Bithumb) PlaceTrade(orderCurrency, transactionType string, units float6 response := OrderPlace{} params := url.Values{} - params.Set("order_currency", common.StringToUpper(orderCurrency)) + params.Set("order_currency", strings.ToUpper(orderCurrency)) params.Set("Payment_currency", "KRW") - params.Set("type", common.StringToUpper(transactionType)) + params.Set("type", strings.ToUpper(transactionType)) params.Set("units", strconv.FormatFloat(units, 'f', -1, 64)) params.Set("price", strconv.FormatInt(price, 10)) @@ -346,9 +347,9 @@ func (b *Bithumb) ModifyTrade(orderID, orderCurrency, transactionType string, un response := OrderPlace{} params := url.Values{} - params.Set("order_currency", common.StringToUpper(orderCurrency)) + params.Set("order_currency", strings.ToUpper(orderCurrency)) params.Set("Payment_currency", "KRW") - params.Set("type", common.StringToUpper(transactionType)) + params.Set("type", strings.ToUpper(transactionType)) params.Set("units", strconv.FormatFloat(units, 'f', -1, 64)) params.Set("price", strconv.FormatInt(price, 10)) params.Set("order_id", orderID) @@ -367,9 +368,9 @@ func (b *Bithumb) GetOrderDetails(orderID, transactionType, currency string) (Or response := OrderDetails{} params := url.Values{} - params.Set("order_id", common.StringToUpper(orderID)) + params.Set("order_id", strings.ToUpper(orderID)) params.Set("type", transactionType) - params.Set("currency", common.StringToUpper(currency)) + params.Set("currency", strings.ToUpper(currency)) return response, b.SendAuthenticatedHTTPRequest(privateOrderDetail, params, &response) @@ -384,9 +385,9 @@ func (b *Bithumb) CancelTrade(transactionType, orderID, currency string) (Action response := ActionStatus{} params := url.Values{} - params.Set("order_id", common.StringToUpper(orderID)) - params.Set("type", common.StringToUpper(transactionType)) - params.Set("currency", common.StringToUpper(currency)) + params.Set("order_id", strings.ToUpper(orderID)) + params.Set("type", strings.ToUpper(transactionType)) + params.Set("currency", strings.ToUpper(currency)) return response, b.SendAuthenticatedHTTPRequest(privateCancelTrade, nil, &response) @@ -408,7 +409,7 @@ func (b *Bithumb) WithdrawCrypto(address, destination, currency string, units fl if len(destination) > 0 { params.Set("destination", destination) } - params.Set("currency", common.StringToUpper(currency)) + params.Set("currency", strings.ToUpper(currency)) params.Set("units", strconv.FormatFloat(units, 'f', -1, 64)) return response, @@ -450,7 +451,7 @@ func (b *Bithumb) MarketBuyOrder(currency string, units float64) (MarketBuy, err response := MarketBuy{} params := url.Values{} - params.Set("currency", common.StringToUpper(currency)) + params.Set("currency", strings.ToUpper(currency)) params.Set("units", strconv.FormatFloat(units, 'f', -1, 64)) return response, @@ -466,7 +467,7 @@ func (b *Bithumb) MarketSellOrder(currency string, units float64) (MarketSell, e response := MarketSell{} params := url.Values{} - params.Set("currency", common.StringToUpper(currency)) + params.Set("currency", strings.ToUpper(currency)) params.Set("units", strconv.FormatFloat(units, 'f', -1, 64)) return response, diff --git a/exchanges/bithumb/bithumb_wrapper.go b/exchanges/bithumb/bithumb_wrapper.go index e895378d..4164f8bb 100644 --- a/exchanges/bithumb/bithumb_wrapper.go +++ b/exchanges/bithumb/bithumb_wrapper.go @@ -5,6 +5,7 @@ import ( "fmt" "math" "strconv" + "strings" "sync" "time" @@ -301,7 +302,7 @@ func (b *Bithumb) SubmitOrder(p currency.Pair, side exchange.OrderSide, _ exchan func (b *Bithumb) ModifyOrder(action *exchange.ModifyOrder) (string, error) { order, err := b.ModifyTrade(action.OrderID, action.CurrencyPair.Base.String(), - common.StringToLower(action.OrderSide.ToString()), + strings.ToLower(action.OrderSide.ToString()), action.Amount, int64(action.Price)) diff --git a/exchanges/bitmex/bitmex_parameters.go b/exchanges/bitmex/bitmex_parameters.go index 1f39af6f..e08e17d5 100644 --- a/exchanges/bitmex/bitmex_parameters.go +++ b/exchanges/bitmex/bitmex_parameters.go @@ -5,6 +5,7 @@ import ( "net/url" "reflect" "strconv" + "strings" "github.com/thrasher-/gocryptotrader/common" ) @@ -35,7 +36,7 @@ func StructValsToURLVals(v interface{}) (url.Values, error) { if structType.Field(i).Tag != "" { jsonTag := structType.Field(i).Tag.Get("json") if jsonTag != "" { - split := common.SplitStrings(jsonTag, ",") + split := strings.Split(jsonTag, ",") outgoingTag = split[0] } } diff --git a/exchanges/bitmex/bitmex_websocket.go b/exchanges/bitmex/bitmex_websocket.go index 33ad3182..9c240510 100644 --- a/exchanges/bitmex/bitmex_websocket.go +++ b/exchanges/bitmex/bitmex_websocket.go @@ -6,6 +6,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/gorilla/websocket" @@ -152,12 +153,12 @@ func (b *Bitmex) wsHandleIncomingData() { } message := string(resp.Raw) - if common.StringContains(message, "pong") { + if strings.Contains(message, "pong") { pongChan <- 1 continue } - if common.StringContains(message, "ping") { + if strings.Contains(message, "ping") { err = b.wsSend("pong") if err != nil { b.Websocket.DataHandler <- err diff --git a/exchanges/bitstamp/bitstamp.go b/exchanges/bitstamp/bitstamp.go index 0b5931a4..91dc3a0f 100644 --- a/exchanges/bitstamp/bitstamp.go +++ b/exchanges/bitstamp/bitstamp.go @@ -157,7 +157,7 @@ func (b *Bitstamp) GetTicker(currency string, hourly bool) (Ticker, error) { b.API.Endpoints.URL, bitstampAPIVersion, tickerEndpoint, - common.StringToLower(currency), + strings.ToLower(currency), ) return response, b.SendHTTPRequest(path, &response) } @@ -178,7 +178,7 @@ func (b *Bitstamp) GetOrderbook(currency string) (Orderbook, error) { b.API.Endpoints.URL, bitstampAPIVersion, bitstampAPIOrderbook, - common.StringToLower(currency), + strings.ToLower(currency), ) err := b.SendHTTPRequest(path, &resp) @@ -244,7 +244,7 @@ func (b *Bitstamp) GetTransactions(currencyPair string, values url.Values) ([]Tr b.API.Endpoints.URL, bitstampAPIVersion, bitstampAPITransactions, - common.StringToLower(currencyPair), + strings.ToLower(currencyPair), ), values, ) @@ -339,7 +339,7 @@ func (b *Bitstamp) GetUserTransactions(currencyPair string) ([]UserTransactions, func (b *Bitstamp) GetOpenOrders(currencyPair string) ([]Order, error) { var resp []Order path := fmt.Sprintf( - "%s/%s", bitstampAPIOpenOrders, common.StringToLower(currencyPair), + "%s/%s", bitstampAPIOpenOrders, strings.ToLower(currencyPair), ) return resp, b.SendAuthenticatedHTTPRequest(path, true, nil, &resp) @@ -385,10 +385,10 @@ func (b *Bitstamp) PlaceOrder(currencyPair string, price, amount float64, buy, m orderType = exchange.SellOrderSide.ToLower().ToString() } - path := fmt.Sprintf("%s/%s", orderType, common.StringToLower(currencyPair)) + path := fmt.Sprintf("%s/%s", orderType, strings.ToLower(currencyPair)) if market { - path = fmt.Sprintf("%s/%s/%s", orderType, bitstampAPIMarket, common.StringToLower(currencyPair)) + path = fmt.Sprintf("%s/%s/%s", orderType, bitstampAPIMarket, strings.ToLower(currencyPair)) } return response, @@ -428,7 +428,7 @@ func (b *Bitstamp) CryptoWithdrawal(amount float64, address, symbol, destTag str resp := CryptoWithdrawalResponse{} var endpoint string - switch common.StringToLower(symbol) { + switch strings.ToLower(symbol) { case "btc": if instant { req.Add("instant", "1") @@ -586,7 +586,7 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, v2 bool, values url hmac := crypto.GetHMAC(crypto.HashSHA256, []byte(n+b.API.Credentials.ClientID+b.API.Credentials.Key), []byte(b.API.Credentials.Secret)) - values.Set("signature", common.StringToUpper(crypto.HexEncodeToString(hmac))) + values.Set("signature", strings.ToUpper(crypto.HexEncodeToString(hmac))) if v2 { path = fmt.Sprintf("%s/v%s/%s/", b.API.Endpoints.URL, bitstampAPIVersion, path) diff --git a/exchanges/bitstamp/bitstamp_websocket.go b/exchanges/bitstamp/bitstamp_websocket.go index 7526907d..aeb61fbd 100644 --- a/exchanges/bitstamp/bitstamp_websocket.go +++ b/exchanges/bitstamp/bitstamp_websocket.go @@ -6,6 +6,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/gorilla/websocket" @@ -117,8 +118,8 @@ func (b *Bitstamp) WsHandleData() { continue } - currencyPair := common.SplitStrings(wsResponse.Channel, "_") - p := currency.NewPairFromString(common.StringToUpper(currencyPair[3])) + currencyPair := strings.Split(wsResponse.Channel, "_") + p := currency.NewPairFromString(strings.ToUpper(currencyPair[3])) err = b.wsUpdateOrderbook(wsOrderBookTemp.Data, p, assets.AssetTypeSpot) if err != nil { @@ -135,8 +136,8 @@ func (b *Bitstamp) WsHandleData() { continue } - currencyPair := common.SplitStrings(wsResponse.Channel, "_") - p := currency.NewPairFromString(common.StringToUpper(currencyPair[2])) + currencyPair := strings.Split(wsResponse.Channel, "_") + p := currency.NewPairFromString(strings.ToUpper(currencyPair[2])) b.Websocket.DataHandler <- exchange.TradeData{ Price: wsTradeTemp.Data.Price, diff --git a/exchanges/bitstamp/bitstamp_wrapper.go b/exchanges/bitstamp/bitstamp_wrapper.go index 1e72fc03..973de297 100644 --- a/exchanges/bitstamp/bitstamp_wrapper.go +++ b/exchanges/bitstamp/bitstamp_wrapper.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "strconv" + "strings" "sync" "time" @@ -155,7 +156,7 @@ func (b *Bitstamp) FetchTradablePairs(asset assets.AssetType) ([]string, error) continue } - pair := common.SplitStrings(pairs[x].Name, "/") + pair := strings.Split(pairs[x].Name, "/") products = append(products, pair[0]+pair[1]) } diff --git a/exchanges/bittrex/bittrex.go b/exchanges/bittrex/bittrex.go index 8da32db1..57dd26fd 100644 --- a/exchanges/bittrex/bittrex.go +++ b/exchanges/bittrex/bittrex.go @@ -6,8 +6,8 @@ import ( "net/http" "net/url" "strconv" + "strings" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/common/crypto" "github.com/thrasher-/gocryptotrader/currency" exchange "github.com/thrasher-/gocryptotrader/exchanges" @@ -96,7 +96,7 @@ func (b *Bittrex) GetCurrencies() (Currency, error) { func (b *Bittrex) GetTicker(currencyPair string) (Ticker, error) { tick := Ticker{} path := fmt.Sprintf("%s/%s?market=%s", b.API.Endpoints.URL, bittrexAPIGetTicker, - common.StringToUpper(currencyPair), + strings.ToUpper(currencyPair), ) if err := b.SendHTTPRequest(path, &tick); err != nil { @@ -130,7 +130,7 @@ func (b *Bittrex) GetMarketSummaries() (MarketSummary, error) { func (b *Bittrex) GetMarketSummary(currencyPair string) (MarketSummary, error) { var summary MarketSummary path := fmt.Sprintf("%s/%s?market=%s", b.API.Endpoints.URL, - bittrexAPIGetMarketSummary, common.StringToLower(currencyPair), + bittrexAPIGetMarketSummary, strings.ToLower(currencyPair), ) if err := b.SendHTTPRequest(path, &summary); err != nil { @@ -153,7 +153,7 @@ func (b *Bittrex) GetMarketSummary(currencyPair string) (MarketSummary, error) { func (b *Bittrex) GetOrderbook(currencyPair string) (OrderBooks, error) { var orderbooks OrderBooks path := fmt.Sprintf("%s/%s?market=%s&type=both&depth=50", b.API.Endpoints.URL, - bittrexAPIGetOrderbook, common.StringToUpper(currencyPair), + bittrexAPIGetOrderbook, strings.ToUpper(currencyPair), ) if err := b.SendHTTPRequest(path, &orderbooks); err != nil { @@ -171,7 +171,7 @@ func (b *Bittrex) GetOrderbook(currencyPair string) (OrderBooks, error) { func (b *Bittrex) GetMarketHistory(currencyPair string) (MarketHistory, error) { var marketHistoriae MarketHistory path := fmt.Sprintf("%s/%s?market=%s", b.API.Endpoints.URL, - bittrexAPIGetMarketHistory, common.StringToUpper(currencyPair), + bittrexAPIGetMarketHistory, strings.ToUpper(currencyPair), ) if err := b.SendHTTPRequest(path, &marketHistoriae); err != nil { diff --git a/exchanges/btcmarkets/btcmarkets.go b/exchanges/btcmarkets/btcmarkets.go index d6c98144..84fa534a 100644 --- a/exchanges/btcmarkets/btcmarkets.go +++ b/exchanges/btcmarkets/btcmarkets.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/url" + "strings" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/common/crypto" @@ -75,8 +76,8 @@ func (b *BTCMarkets) GetTicker(firstPair, secondPair string) (Ticker, error) { tick := Ticker{} path := fmt.Sprintf("%s/market/%s/%s/tick", b.API.Endpoints.URL, - common.StringToUpper(firstPair), - common.StringToUpper(secondPair)) + strings.ToUpper(firstPair), + strings.ToUpper(secondPair)) return tick, b.SendHTTPRequest(path, &tick) } @@ -87,8 +88,8 @@ func (b *BTCMarkets) GetOrderbook(firstPair, secondPair string) (Orderbook, erro orderbook := Orderbook{} path := fmt.Sprintf("%s/market/%s/%s/orderbook", b.API.Endpoints.URL, - common.StringToUpper(firstPair), - common.StringToUpper(secondPair)) + strings.ToUpper(firstPair), + strings.ToUpper(secondPair)) return orderbook, b.SendHTTPRequest(path, &orderbook) } @@ -99,8 +100,8 @@ func (b *BTCMarkets) GetOrderbook(firstPair, secondPair string) (Orderbook, erro func (b *BTCMarkets) GetTrades(firstPair, secondPair string, values url.Values) ([]Trade, error) { var trades []Trade path := common.EncodeURLValues(fmt.Sprintf("%s/market/%s/%s/trades", - b.API.Endpoints.URL, common.StringToUpper(firstPair), - common.StringToUpper(secondPair)), values) + b.API.Endpoints.URL, strings.ToUpper(firstPair), + strings.ToUpper(secondPair)), values) return trades, b.SendHTTPRequest(path, &trades) } @@ -118,8 +119,8 @@ func (b *BTCMarkets) NewOrder(instrument, currency string, price, amount float64 newVolume := int64(amount * float64(common.SatoshisPerBTC)) order := OrderToGo{ - Currency: common.StringToUpper(currency), - Instrument: common.StringToUpper(instrument), + Currency: strings.ToUpper(currency), + Instrument: strings.ToUpper(instrument), Price: newPrice, Volume: newVolume, OrderSide: orderSide, @@ -172,10 +173,10 @@ func (b *BTCMarkets) GetOrders(currency, instrument string, limit, since int64, req := make(map[string]interface{}) if currency != "" { - req["currency"] = common.StringToUpper(currency) + req["currency"] = strings.ToUpper(currency) } if instrument != "" { - req["instrument"] = common.StringToUpper(instrument) + req["instrument"] = strings.ToUpper(instrument) } if limit != 0 { req["limit"] = limit @@ -312,7 +313,7 @@ func (b *BTCMarkets) WithdrawCrypto(amount float64, currency, address string) (s req := WithdrawRequestCrypto{ Amount: newAmount, - Currency: common.StringToUpper(currency), + Currency: strings.ToUpper(currency), Address: address, } diff --git a/exchanges/exchange.go b/exchanges/exchange.go index 75869c9f..37ba6b3f 100644 --- a/exchanges/exchange.go +++ b/exchanges/exchange.go @@ -8,7 +8,6 @@ import ( "strings" "time" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/common/crypto" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency" @@ -489,7 +488,7 @@ func (e *Base) ValidateAPICredentials() bool { if e.API.CredentialsValidator.RequiresPEM { if e.API.Credentials.PEMKey == "" || - common.StringContains(e.API.Credentials.PEMKey, "JUSTADUMMY") { + strings.Contains(e.API.Credentials.PEMKey, "JUSTADUMMY") { log.Warnf("exchange %s requires API PEM key but default/empty one set", e.Name) return false diff --git a/exchanges/exchange_types.go b/exchanges/exchange_types.go index 1b4a5ba0..23060843 100644 --- a/exchanges/exchange_types.go +++ b/exchanges/exchange_types.go @@ -6,7 +6,6 @@ import ( "strings" "time" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency" "github.com/thrasher-/gocryptotrader/exchanges/assets" @@ -164,7 +163,7 @@ const ( // ToLower changes the ordertype to lower case func (o OrderType) ToLower() OrderType { - return OrderType(common.StringToLower(string(o))) + return OrderType(strings.ToLower(string(o))) } // ToString changes the ordertype to the exchange standard and returns a string @@ -186,7 +185,7 @@ const ( // ToLower changes the ordertype to lower case func (o OrderSide) ToLower() OrderSide { - return OrderSide(common.StringToLower(string(o))) + return OrderSide(strings.ToLower(string(o))) } // ToString changes the ordertype to the exchange standard and returns a string diff --git a/exchanges/exmo/exmo.go b/exchanges/exmo/exmo.go index 5736ffcb..5833ddf0 100644 --- a/exchanges/exmo/exmo.go +++ b/exchanges/exmo/exmo.go @@ -238,7 +238,7 @@ func (e *EXMO) WithdrawCryptocurrency(currency, address, invoice string, amount v.Set("currency", currency) v.Set("address", address) - if common.StringToUpper(currency) == "XRP" { + if strings.ToUpper(currency) == "XRP" { v.Set(invoice, invoice) } diff --git a/exchanges/gateio/gateio.go b/exchanges/gateio/gateio.go index 4146c541..7aeda956 100644 --- a/exchanges/gateio/gateio.go +++ b/exchanges/gateio/gateio.go @@ -11,6 +11,7 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/gocryptotrader/common/convert" "github.com/thrasher-/gocryptotrader/common/crypto" "github.com/thrasher-/gocryptotrader/currency" exchange "github.com/thrasher-/gocryptotrader/exchanges" @@ -214,31 +215,31 @@ func (g *Gateio) GetSpotKline(arg KlinesRequestParams) ([]*KLineResponse, error) for _, k := range rawKlineDatas { otString, _ := strconv.ParseFloat(k[0].(string), 64) - ot, err := common.TimeFromUnixTimestampFloat(otString) + ot, err := convert.TimeFromUnixTimestampFloat(otString) if err != nil { return nil, fmt.Errorf("cannot parse Kline.OpenTime. Err: %s", err) } - _vol, err := common.FloatFromString(k[1]) + _vol, err := convert.FloatFromString(k[1]) if err != nil { return nil, fmt.Errorf("cannot parse Kline.Volume. Err: %s", err) } - _id, err := common.FloatFromString(k[0]) + _id, err := convert.FloatFromString(k[0]) if err != nil { return nil, fmt.Errorf("cannot parse Kline.Id. Err: %s", err) } - _close, err := common.FloatFromString(k[2]) + _close, err := convert.FloatFromString(k[2]) if err != nil { return nil, fmt.Errorf("cannot parse Kline.Close. Err: %s", err) } - _high, err := common.FloatFromString(k[3]) + _high, err := convert.FloatFromString(k[3]) if err != nil { return nil, fmt.Errorf("cannot parse Kline.High. Err: %s", err) } - _low, err := common.FloatFromString(k[4]) + _low, err := convert.FloatFromString(k[4]) if err != nil { return nil, fmt.Errorf("cannot parse Kline.Low. Err: %s", err) } - _open, err := common.FloatFromString(k[5]) + _open, err := convert.FloatFromString(k[5]) if err != nil { return nil, fmt.Errorf("cannot parse Kline.Open. Err: %s", err) } diff --git a/exchanges/gateio/gateio_websocket.go b/exchanges/gateio/gateio_websocket.go index 1caa17ac..80aeb672 100644 --- a/exchanges/gateio/gateio_websocket.go +++ b/exchanges/gateio/gateio_websocket.go @@ -118,7 +118,7 @@ func (g *Gateio) WsHandleData() { } if result.Error.Code != 0 { - if common.StringContains(result.Error.Message, "authentication") { + if strings.Contains(result.Error.Message, "authentication") { g.Websocket.DataHandler <- fmt.Errorf("%v - WebSocket authentication failed ", g.GetName()) g.API.AuthenticatedSupport = false @@ -170,7 +170,7 @@ func (g *Gateio) WsHandleData() { } switch { - case common.StringContains(result.Method, "ticker"): + case strings.Contains(result.Method, "ticker"): var ticker WebsocketTicker var c string err = common.JSONDecode(result.Params[1], &ticker) @@ -197,7 +197,7 @@ func (g *Gateio) WsHandleData() { LowPrice: ticker.Low, } - case common.StringContains(result.Method, "trades"): + case strings.Contains(result.Method, "trades"): var trades []WebsocketTrade var c string err = common.JSONDecode(result.Params[1], &trades) @@ -224,7 +224,7 @@ func (g *Gateio) WsHandleData() { } } - case common.StringContains(result.Method, "depth"): + case strings.Contains(result.Method, "depth"): var IsSnapshot bool var c string var data = make(map[string][][]string) @@ -312,7 +312,7 @@ func (g *Gateio) WsHandleData() { Exchange: g.GetName(), } - case common.StringContains(result.Method, "kline"): + case strings.Contains(result.Method, "kline"): var data []interface{} err = common.JSONDecode(result.Params[0], &data) if err != nil { diff --git a/exchanges/gemini/gemini.go b/exchanges/gemini/gemini.go index e2d9a197..423124ba 100644 --- a/exchanges/gemini/gemini.go +++ b/exchanges/gemini/gemini.go @@ -133,7 +133,7 @@ func (g *Gemini) GetTicker(currencyPair string) (Ticker, error) { ticker.Volume.Currency, _ = strconv.ParseFloat(resp.Volume[currencyPair[0:3]].(string), 64) - if common.StringContains(currencyPair, "USD") { + if strings.Contains(currencyPair, "USD") { ticker.Volume.USD, _ = strconv.ParseFloat(resp.Volume["USD"].(string), 64) } else { if resp.Volume["ETH"] != nil { @@ -377,7 +377,7 @@ func (g *Gemini) WithdrawCrypto(address, currency string, amount float64) (Withd req["address"] = address req["amount"] = strconv.FormatFloat(amount, 'f', -1, 64) - err := g.SendAuthenticatedHTTPRequest(http.MethodPost, geminiWithdraw+common.StringToLower(currency), req, &response) + err := g.SendAuthenticatedHTTPRequest(http.MethodPost, geminiWithdraw+strings.ToLower(currency), req, &response) if err != nil { return response, err } diff --git a/exchanges/hitbtc/hitbtc_wrapper.go b/exchanges/hitbtc/hitbtc_wrapper.go index 4a52893c..7eea50c1 100644 --- a/exchanges/hitbtc/hitbtc_wrapper.go +++ b/exchanges/hitbtc/hitbtc_wrapper.go @@ -296,8 +296,8 @@ func (h *HitBTC) SubmitOrder(p currency.Pair, side exchange.OrderSide, orderType response, err := h.PlaceOrder(p.String(), price, amount, - common.StringToLower(orderType.ToString()), - common.StringToLower(side.ToString())) + strings.ToLower(orderType.ToString()), + strings.ToLower(side.ToString())) if response.OrderNumber > 0 { submitOrderResponse.OrderID = fmt.Sprintf("%v", response.OrderNumber) diff --git a/exchanges/huobi/huobi_websocket.go b/exchanges/huobi/huobi_websocket.go index de2e20d3..886b1fed 100644 --- a/exchanges/huobi/huobi_websocket.go +++ b/exchanges/huobi/huobi_websocket.go @@ -8,6 +8,7 @@ import ( "io/ioutil" "net/http" "net/url" + "strings" "time" "github.com/gorilla/websocket" @@ -126,7 +127,7 @@ func (h *HUOBI) WsHandleData() { } switch { - case common.StringContains(init.Channel, "depth"): + case strings.Contains(init.Channel, "depth"): var depth WsDepth err := common.JSONDecode(resp.Raw, &depth) if err != nil { @@ -134,11 +135,11 @@ func (h *HUOBI) WsHandleData() { continue } - data := common.SplitStrings(depth.Channel, ".") + data := strings.Split(depth.Channel, ".") h.WsProcessOrderbook(&depth, data[1]) - case common.StringContains(init.Channel, "kline"): + case strings.Contains(init.Channel, "kline"): var kline WsKline err := common.JSONDecode(resp.Raw, &kline) if err != nil { @@ -146,7 +147,7 @@ func (h *HUOBI) WsHandleData() { continue } - data := common.SplitStrings(kline.Channel, ".") + data := strings.Split(kline.Channel, ".") h.Websocket.DataHandler <- exchange.KlineData{ Timestamp: time.Unix(0, kline.Timestamp), @@ -160,7 +161,7 @@ func (h *HUOBI) WsHandleData() { Volume: kline.Tick.Volume, } - case common.StringContains(init.Channel, "trade"): + case strings.Contains(init.Channel, "trade"): var trade WsTrade err := common.JSONDecode(resp.Raw, &trade) if err != nil { @@ -168,7 +169,7 @@ func (h *HUOBI) WsHandleData() { continue } - data := common.SplitStrings(trade.Channel, ".") + data := strings.Split(trade.Channel, ".") h.Websocket.DataHandler <- exchange.TradeData{ Exchange: h.GetName(), diff --git a/exchanges/huobi/huobi_wrapper.go b/exchanges/huobi/huobi_wrapper.go index 23a59cf1..48905574 100644 --- a/exchanges/huobi/huobi_wrapper.go +++ b/exchanges/huobi/huobi_wrapper.go @@ -390,7 +390,7 @@ func (h *HUOBI) SubmitOrder(p currency.Pair, side exchange.OrderSide, orderType var params = SpotNewOrderRequestParams{ Amount: amount, Source: "api", - Symbol: common.StringToLower(p.String()), + Symbol: strings.ToLower(p.String()), AccountID: int(accountID), } diff --git a/exchanges/huobihadax/huobihadax.go b/exchanges/huobihadax/huobihadax.go index 691b7532..ace01ae7 100644 --- a/exchanges/huobihadax/huobihadax.go +++ b/exchanges/huobihadax/huobihadax.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "sync" "time" @@ -843,7 +844,7 @@ func (h *HUOBIHADAX) GetDepositWithdrawalHistory(associatedID, currency string, vals.Set("from", associatedID) vals.Set("size", strconv.FormatInt(size, 10)) - vals.Set("currency", common.StringToLower(currency)) + vals.Set("currency", strings.ToLower(currency)) err := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobiHadaxDepositAddress, diff --git a/exchanges/huobihadax/huobihadax_websocket.go b/exchanges/huobihadax/huobihadax_websocket.go index 75b03a7e..7ef4ca59 100644 --- a/exchanges/huobihadax/huobihadax_websocket.go +++ b/exchanges/huobihadax/huobihadax_websocket.go @@ -8,6 +8,7 @@ import ( "io/ioutil" "net/http" "net/url" + "strings" "time" "github.com/gorilla/websocket" @@ -129,7 +130,7 @@ func (h *HUOBIHADAX) WsHandleData() { } switch { - case common.StringContains(init.Channel, "depth"): + case strings.Contains(init.Channel, "depth"): var depth WsDepth err := common.JSONDecode(resp.Raw, &depth) if err != nil { @@ -137,11 +138,11 @@ func (h *HUOBIHADAX) WsHandleData() { continue } - data := common.SplitStrings(depth.Channel, ".") + data := strings.Split(depth.Channel, ".") h.WsProcessOrderbook(&depth, data[1]) - case common.StringContains(init.Channel, "kline"): + case strings.Contains(init.Channel, "kline"): var kline WsKline err := common.JSONDecode(resp.Raw, &kline) if err != nil { @@ -149,7 +150,7 @@ func (h *HUOBIHADAX) WsHandleData() { continue } - data := common.SplitStrings(kline.Channel, ".") + data := strings.Split(kline.Channel, ".") h.Websocket.DataHandler <- exchange.KlineData{ Timestamp: time.Unix(0, kline.Timestamp), @@ -163,7 +164,7 @@ func (h *HUOBIHADAX) WsHandleData() { Volume: kline.Tick.Volume, } - case common.StringContains(init.Channel, "trade"): + case strings.Contains(init.Channel, "trade"): var trade WsTrade err := common.JSONDecode(resp.Raw, &trade) if err != nil { @@ -171,7 +172,7 @@ func (h *HUOBIHADAX) WsHandleData() { continue } - data := common.SplitStrings(trade.Channel, ".") + data := strings.Split(trade.Channel, ".") h.Websocket.DataHandler <- exchange.TradeData{ Exchange: h.GetName(), diff --git a/exchanges/huobihadax/huobihadax_wrapper.go b/exchanges/huobihadax/huobihadax_wrapper.go index 67b2412b..6923b317 100644 --- a/exchanges/huobihadax/huobihadax_wrapper.go +++ b/exchanges/huobihadax/huobihadax_wrapper.go @@ -351,7 +351,7 @@ func (h *HUOBIHADAX) SubmitOrder(p currency.Pair, side exchange.OrderSide, order var params = SpotNewOrderRequestParams{ Amount: amount, Source: "api", - Symbol: common.StringToLower(p.String()), + Symbol: strings.ToLower(p.String()), AccountID: int(accountID), } diff --git a/exchanges/kraken/kraken.go b/exchanges/kraken/kraken.go index a6502e7a..be73a5ac 100644 --- a/exchanges/kraken/kraken.go +++ b/exchanges/kraken/kraken.go @@ -10,7 +10,6 @@ import ( "sync" "github.com/gorilla/websocket" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/common/crypto" "github.com/thrasher-/gocryptotrader/currency" exchange "github.com/thrasher-/gocryptotrader/exchanges" @@ -751,8 +750,8 @@ func (k *Kraken) GetTradeVolume(feeinfo bool, symbol ...string) (TradeVolumeResp func (k *Kraken) AddOrder(symbol, side, orderType string, volume, price, price2, leverage float64, args *AddOrderOptions) (AddOrderResponse, error) { params := url.Values{ "pair": {symbol}, - "type": {common.StringToLower(side)}, - "ordertype": {common.StringToLower(orderType)}, + "type": {strings.ToLower(side)}, + "ordertype": {strings.ToLower(orderType)}, "volume": {strconv.FormatFloat(volume, 'f', -1, 64)}, } diff --git a/exchanges/kraken/kraken_wrapper.go b/exchanges/kraken/kraken_wrapper.go index 874e61b0..7a98bc28 100644 --- a/exchanges/kraken/kraken_wrapper.go +++ b/exchanges/kraken/kraken_wrapper.go @@ -172,7 +172,7 @@ func (k *Kraken) FetchTradablePairs(asset assets.AssetType) ([]string, error) { var products []string for i := range pairs { v := pairs[i] - if common.StringContains(v.Altname, ".d") { + if strings.Contains(v.Altname, ".d") { continue } if v.Base[0] == 'X' { @@ -214,8 +214,8 @@ func (k *Kraken) UpdateTicker(p currency.Pair, assetType assets.AssetType) (tick for _, x := range pairs { for y, z := range tickers { - if !common.StringContains(y, x.Base.Upper().String()) || - !common.StringContains(y, x.Quote.Upper().String()) { + if !strings.Contains(y, x.Base.Upper().String()) || + !strings.Contains(y, x.Quote.Upper().String()) { continue } var tp ticker.Price diff --git a/exchanges/lakebtc/lakebtc.go b/exchanges/lakebtc/lakebtc.go index 7a4877ab..8fec64cc 100644 --- a/exchanges/lakebtc/lakebtc.go +++ b/exchanges/lakebtc/lakebtc.go @@ -52,7 +52,7 @@ func (l *LakeBTC) GetTicker() (map[string]Ticker, error) { for k, v := range response { var tick Ticker - key := common.StringToUpper(k) + key := strings.ToUpper(k) if v.Ask != nil { tick.Ask, _ = strconv.ParseFloat(v.Ask.(string), 64) } @@ -82,7 +82,7 @@ func (l *LakeBTC) GetOrderBook(currency string) (Orderbook, error) { Bids [][]string `json:"bids"` Asks [][]string `json:"asks"` } - path := fmt.Sprintf("%s/%s?symbol=%s", l.API.Endpoints.URL, lakeBTCOrderbook, common.StringToLower(currency)) + path := fmt.Sprintf("%s/%s?symbol=%s", l.API.Endpoints.URL, lakeBTCOrderbook, strings.ToLower(currency)) resp := Response{} err := l.SendHTTPRequest(path, &resp) if err != nil { @@ -122,7 +122,7 @@ func (l *LakeBTC) GetOrderBook(currency string) (Orderbook, error) { // GetTradeHistory returns the trade history for a given currency pair func (l *LakeBTC) GetTradeHistory(currency string) ([]TradeHistory, error) { - path := fmt.Sprintf("%s/%s?symbol=%s", l.API.Endpoints.URL, lakeBTCTrades, common.StringToLower(currency)) + path := fmt.Sprintf("%s/%s?symbol=%s", l.API.Endpoints.URL, lakeBTCTrades, strings.ToLower(currency)) var resp []TradeHistory return resp, l.SendHTTPRequest(path, &resp) } @@ -172,7 +172,7 @@ func (l *LakeBTC) GetOrders(orders []int64) ([]Orders, error) { var resp []Orders return resp, - l.SendAuthenticatedHTTPRequest(lakeBTCGetOrders, common.JoinStrings(ordersStr, ","), &resp) + l.SendAuthenticatedHTTPRequest(lakeBTCGetOrders, strings.Join(ordersStr, ","), &resp) } // CancelExistingOrder cancels an order by ID number and returns an error @@ -201,7 +201,7 @@ func (l *LakeBTC) CancelExistingOrders(orderIDs []string) error { } resp := Response{} - params := common.JoinStrings(orderIDs, ",") + params := strings.Join(orderIDs, ",") err := l.SendAuthenticatedHTTPRequest(lakeBTCCancelOrder, params, &resp) if err != nil { return err @@ -271,7 +271,7 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string, result int postData := make(map[string]interface{}) postData["method"] = method postData["id"] = 1 - postData["params"] = common.SplitStrings(params, ",") + postData["params"] = strings.Split(params, ",") data, err := common.JSONEncode(postData) if err != nil { diff --git a/exchanges/lakebtc/lakebtc_wrapper.go b/exchanges/lakebtc/lakebtc_wrapper.go index ae8a6d9c..9b563996 100644 --- a/exchanges/lakebtc/lakebtc_wrapper.go +++ b/exchanges/lakebtc/lakebtc_wrapper.go @@ -133,7 +133,7 @@ func (l *LakeBTC) FetchTradablePairs(asset assets.AssetType) ([]string, error) { var currencies []string for x := range result { - currencies = append(currencies, common.StringToUpper(x)) + currencies = append(currencies, strings.ToUpper(x)) } return currencies, nil diff --git a/exchanges/localbitcoins/localbitcoins.go b/exchanges/localbitcoins/localbitcoins.go index fe61955a..5a34882b 100644 --- a/exchanges/localbitcoins/localbitcoins.go +++ b/exchanges/localbitcoins/localbitcoins.go @@ -684,7 +684,7 @@ func (l *LocalBitcoins) SendAuthenticatedHTTPRequest(method, path string, params headers := make(map[string]string) headers["Apiauth-Key"] = l.API.Credentials.Key headers["Apiauth-Nonce"] = n - headers["Apiauth-Signature"] = common.StringToUpper(crypto.HexEncodeToString(hmac)) + headers["Apiauth-Signature"] = strings.ToUpper(crypto.HexEncodeToString(hmac)) headers["Content-Type"] = "application/x-www-form-urlencoded" if l.Verbose { diff --git a/exchanges/request/request.go b/exchanges/request/request.go index 388afd94..93c9a5f9 100644 --- a/exchanges/request/request.go +++ b/exchanges/request/request.go @@ -10,6 +10,7 @@ import ( "net/http" "net/http/httputil" "net/url" + "strings" "sync" "time" @@ -327,7 +328,7 @@ func (r *Requester) DoRequest(req *http.Request, path string, body io.Reader, re default: switch { - case common.StringContains(resp.Header.Get("Content-Type"), "application/json"): + case strings.Contains(resp.Header.Get("Content-Type"), "application/json"): reader = resp.Body default: diff --git a/exchanges/ticker/ticker.go b/exchanges/ticker/ticker.go index f8732a96..e30bcaf7 100644 --- a/exchanges/ticker/ticker.go +++ b/exchanges/ticker/ticker.go @@ -3,10 +3,10 @@ package ticker import ( "errors" "strconv" + "strings" "sync" "time" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency" "github.com/thrasher-/gocryptotrader/exchanges/assets" ) @@ -45,7 +45,7 @@ type Ticker struct { // PriceToString returns the string version of a stored price field func (t *Ticker) PriceToString(p currency.Pair, priceType string, tickerType assets.AssetType) string { - priceType = common.StringToLower(priceType) + priceType = strings.ToLower(priceType) switch priceType { case "last": diff --git a/exchanges/websocket_test.go b/exchanges/websocket_test.go index 792d25b1..8917beef 100644 --- a/exchanges/websocket_test.go +++ b/exchanges/websocket_test.go @@ -389,7 +389,7 @@ func TestSubscriptionWithExistingEntry(t *testing.T) { w.SetChannelSubscriber(placeholderSubscriber) w.subscribeToChannels() if len(w.subscribedChannels) != 1 { - t.Errorf("Subscription should not have occured") + t.Errorf("Subscription should not have occurred") } } @@ -410,7 +410,7 @@ func TestUnsubscriptionWithExistingEntry(t *testing.T) { w.SetChannelUnsubscriber(placeholderSubscriber) w.unsubscribeToChannels() if len(w.subscribedChannels) != 1 { - t.Errorf("Unsubscription should not have occured") + t.Errorf("Unsubscription should not have occurred") } } diff --git a/exchanges/yobit/yobit_wrapper.go b/exchanges/yobit/yobit_wrapper.go index 2244ed68..81a12f69 100644 --- a/exchanges/yobit/yobit_wrapper.go +++ b/exchanges/yobit/yobit_wrapper.go @@ -138,7 +138,7 @@ func (y *Yobit) FetchTradablePairs(asset assets.AssetType) ([]string, error) { var currencies []string for x := range info.Pairs { - currencies = append(currencies, common.StringToUpper(x)) + currencies = append(currencies, strings.ToUpper(x)) } return currencies, nil diff --git a/exchanges/zb/zb.go b/exchanges/zb/zb.go index 349f8895..04cfd44e 100644 --- a/exchanges/zb/zb.go +++ b/exchanges/zb/zb.go @@ -13,6 +13,7 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/gocryptotrader/common/convert" "github.com/thrasher-/gocryptotrader/common/crypto" "github.com/thrasher-/gocryptotrader/currency" exchange "github.com/thrasher-/gocryptotrader/exchanges" @@ -66,7 +67,7 @@ func (z *ZB) SpotNewOrder(arg SpotNewOrderRequestParams) (int64, error) { return 0, err } if result.Code != 1000 { - return 0, fmt.Errorf("unsucessful new order, message: %s code: %d", result.Message, result.Code) + return 0, fmt.Errorf("unsuccessful new order, message: %s code: %d", result.Message, result.Code) } newOrderID, err := strconv.ParseInt(result.ID, 10, 64) if err != nil { @@ -252,7 +253,7 @@ func (z *ZB) GetSpotKline(arg KlinesRequestParams) (KLineResponse, error) { return res, errors.New("zb rawKlines unmarshal failed") } for _, k := range rawKlineDatas { - ot, err := common.TimeFromUnixTimestampFloat(k[0]) + ot, err := convert.TimeFromUnixTimestampFloat(k[0]) if err != nil { return res, errors.New("zb cannot parse Kline.OpenTime") } diff --git a/exchanges/zb/zb_websocket.go b/exchanges/zb/zb_websocket.go index 4d5bc2ac..6e44beef 100644 --- a/exchanges/zb/zb_websocket.go +++ b/exchanges/zb/zb_websocket.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/url" + "strings" "time" "github.com/gorilla/websocket" @@ -89,7 +90,7 @@ func (z *ZB) WsHandleData() { continue } switch { - case common.StringContains(result.Channel, "markets"): + case strings.Contains(result.Channel, "markets"): if !result.Success { z.Websocket.DataHandler <- fmt.Errorf("zb_websocket.go error - unsuccessful market response %s", wsErrCodes[result.Code]) continue @@ -102,8 +103,8 @@ func (z *ZB) WsHandleData() { continue } - case common.StringContains(result.Channel, "ticker"): - cPair := common.SplitStrings(result.Channel, "_") + case strings.Contains(result.Channel, "ticker"): + cPair := strings.Split(result.Channel, "_") var ticker WsTicker @@ -123,7 +124,7 @@ func (z *ZB) WsHandleData() { LowPrice: ticker.Data.Low, } - case common.StringContains(result.Channel, "depth"): + case strings.Contains(result.Channel, "depth"): var depth WsDepth err := common.JSONDecode(resp.Raw, &depth) if err != nil { @@ -149,7 +150,7 @@ func (z *ZB) WsHandleData() { }) } - channelInfo := common.SplitStrings(result.Channel, "_") + channelInfo := strings.Split(result.Channel, "_") cPair := currency.NewPairFromString(channelInfo[0]) var newOrderBook orderbook.Base @@ -172,7 +173,7 @@ func (z *ZB) WsHandleData() { Exchange: z.GetName(), } - case common.StringContains(result.Channel, "trades"): + case strings.Contains(result.Channel, "trades"): var trades WsTrades err := common.JSONDecode(resp.Raw, &trades) if err != nil { @@ -183,7 +184,7 @@ func (z *ZB) WsHandleData() { // Most up to date trade t := trades.Data[len(trades.Data)-1] - channelInfo := common.SplitStrings(result.Channel, "_") + channelInfo := strings.Split(result.Channel, "_") cPair := currency.NewPairFromString(channelInfo[0]) z.Websocket.DataHandler <- exchange.TradeData{ diff --git a/exchanges/zb/zb_wrapper.go b/exchanges/zb/zb_wrapper.go index 7fad5b7f..ad1d52e6 100644 --- a/exchanges/zb/zb_wrapper.go +++ b/exchanges/zb/zb_wrapper.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "strconv" + "strings" "sync" "time" @@ -179,7 +180,7 @@ func (z *ZB) UpdateTicker(p currency.Pair, assetType assets.AssetType) (ticker.P } for _, x := range z.GetEnabledPairs(assetType) { - currencySplit := common.SplitStrings(z.FormatExchangeCurrency(x, assetType).String(), "_") + currencySplit := strings.Split(z.FormatExchangeCurrency(x, assetType).String(), "_") currency := currencySplit[0] + currencySplit[1] var tp ticker.Price tp.Pair = x @@ -312,7 +313,7 @@ func (z *ZB) SubmitOrder(p currency.Pair, side exchange.OrderSide, _ exchange.Or var params = SpotNewOrderRequestParams{ Amount: amount, Price: price, - Symbol: common.StringToLower(p.String()), + Symbol: strings.ToLower(p.String()), Type: oT, } response, err := z.SpotNewOrder(params) diff --git a/portfolio/portfolio.go b/portfolio/portfolio.go index 24f9456b..c6751422 100644 --- a/portfolio/portfolio.go +++ b/portfolio/portfolio.go @@ -3,6 +3,7 @@ package portfolio import ( "errors" "fmt" + "strings" "time" "github.com/thrasher-/gocryptotrader/common" @@ -182,8 +183,8 @@ func (p *Base) RemoveAddress(address, description string, coinType currency.Code // UpdatePortfolio adds to the portfolio addresses by coin type func (p *Base) UpdatePortfolio(addresses []string, coinType currency.Code) bool { - if common.StringContains(common.JoinStrings(addresses, ","), PortfolioAddressExchange) || - common.StringContains(common.JoinStrings(addresses, ","), PortfolioAddressPersonal) { + if strings.Contains(strings.Join(addresses, ","), PortfolioAddressExchange) || + strings.Contains(strings.Join(addresses, ","), PortfolioAddressPersonal) { return true } @@ -224,7 +225,7 @@ func (p *Base) UpdatePortfolio(addresses []string, coinType currency.Code) bool func (p *Base) GetPortfolioByExchange(exchangeName string) map[currency.Code]float64 { result := make(map[currency.Code]float64) for x := range p.Addresses { - if common.StringContains(p.Addresses[x].Address, exchangeName) { + if strings.Contains(p.Addresses[x].Address, exchangeName) { result[p.Addresses[x].CoinType] = p.Addresses[x].Balance } } @@ -380,7 +381,7 @@ func (p *Base) GetPortfolioSummary() Summary { func (p *Base) GetPortfolioGroupedCoin() map[currency.Code][]string { result := make(map[currency.Code][]string) for _, x := range p.Addresses { - if common.StringContains(x.Description, PortfolioAddressExchange) { + if strings.Contains(x.Description, PortfolioAddressExchange) { continue } result[x.CoinType] = append(result[x.CoinType], x.Address) diff --git a/utils/utils.go b/utils/utils.go index 5aa49b7d..7334aa92 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -2,9 +2,8 @@ package utils import ( "errors" + "path/filepath" "runtime" - - "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -32,5 +31,5 @@ func AdjustGoMaxProcs(maxProcs int) error { // GetTLSDir returns the default TLS dir func GetTLSDir(dir string) string { - return dir + common.GetOSPathSlash() + defaultTLSDir + return filepath.Join(dir, defaultTLSDir) }