diff --git a/alphapointhttp.go b/alphapointhttp.go index c0424583..0eaaeae6 100644 --- a/alphapointhttp.go +++ b/alphapointhttp.go @@ -9,6 +9,7 @@ import ( "time" "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -565,19 +566,19 @@ func (a *Alphapoint) SendRequest(method, path string, data map[string]interface{ headers := make(map[string]string) headers["Content-Type"] = "application/json" path = fmt.Sprintf("%s/ajax/v%s/%s", a.APIUrl, ALPHAPOINT_API_VERSION, path) - PayloadJson, err := JSONEncode(data) + PayloadJson, err := common.JSONEncode(data) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") } - resp, err := SendHTTPRequest(method, path, headers, bytes.NewBuffer(PayloadJson)) + resp, err := common.SendHTTPRequest(method, path, headers, bytes.NewBuffer(PayloadJson)) if err != nil { return err } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") @@ -592,22 +593,22 @@ func (a *Alphapoint) SendAuthenticatedHTTPRequest(method, path string, data map[ nonce := time.Now().UnixNano() nonceStr := strconv.FormatInt(nonce, 10) data["apiNonce"] = nonce - hmac := GetHMAC(HASH_SHA256, []byte(nonceStr+a.UserID+a.APIKey), []byte(a.APISecret)) - data["apiSig"] = StringToUpper(HexEncodeToString(hmac)) + hmac := common.GetHMAC(common.HASH_SHA256, []byte(nonceStr+a.UserID+a.APIKey), []byte(a.APISecret)) + data["apiSig"] = common.StringToUpper(common.HexEncodeToString(hmac)) path = fmt.Sprintf("%s/ajax/v%s/%s", a.APIUrl, ALPHAPOINT_API_VERSION, path) - PayloadJson, err := JSONEncode(data) + PayloadJson, err := common.JSONEncode(data) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") } - resp, err := SendHTTPRequest(method, path, headers, bytes.NewBuffer(PayloadJson)) + resp, err := common.SendHTTPRequest(method, path, headers, bytes.NewBuffer(PayloadJson)) if err != nil { return err } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/alphapointwebsocket.go b/alphapointwebsocket.go index 806fe914..ba6dc4e4 100644 --- a/alphapointwebsocket.go +++ b/alphapointwebsocket.go @@ -1,9 +1,11 @@ package main import ( - "github.com/gorilla/websocket" "log" "net/http" + + "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -64,7 +66,7 @@ func (a *Alphapoint) WebsocketClient() { } msgType := MsgType{} - err := JSONDecode(resp, &msgType) + err := common.JSONDecode(resp, &msgType) if err != nil { log.Println(err) continue @@ -73,7 +75,7 @@ func (a *Alphapoint) WebsocketClient() { switch msgType.MessageType { case "Ticker": ticker := AlphapointWebsocketTicker{} - err = JSONDecode(resp, &ticker) + err = common.JSONDecode(resp, &ticker) if err != nil { log.Println(err) continue diff --git a/anxhttp.go b/anxhttp.go index 937b454c..3513e622 100644 --- a/anxhttp.go +++ b/anxhttp.go @@ -7,6 +7,8 @@ import ( "log" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -111,9 +113,9 @@ func (a *ANX) Setup(exch Exchanges) { a.RESTPollingDelay = exch.RESTPollingDelay a.Verbose = exch.Verbose a.Websocket = exch.Websocket - a.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - a.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - a.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + a.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + a.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + a.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -140,7 +142,7 @@ func (a *ANX) SetAPIKeys(apiKey, apiSecret string) { } a.APIKey = apiKey - result, err := Base64Decode(apiSecret) + result, err := common.Base64Decode(apiSecret) if err != nil { log.Printf("%s unable to decode secret key. Authenticated API support disabled.", a.GetName()) @@ -184,7 +186,7 @@ func (a *ANX) Run() { func (a *ANX) GetTicker(currency string) (ANXTicker, error) { var ticker ANXTicker - err := SendHTTPGetRequest(fmt.Sprintf("%sapi/2/%s/%s", ANX_API_URL, currency, ANX_TICKER), true, &ticker) + err := common.SendHTTPGetRequest(fmt.Sprintf("%sapi/2/%s/%s", ANX_API_URL, currency, ANX_TICKER), true, &ticker) if err != nil { return ANXTicker{}, err } @@ -458,7 +460,7 @@ func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interf } } - PayloadJson, err := JSONEncode(request) + PayloadJson, err := common.JSONEncode(request) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") @@ -468,19 +470,19 @@ func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interf log.Printf("Request JSON: %s\n", PayloadJson) } - hmac := GetHMAC(HASH_SHA512, []byte(path+string("\x00")+string(PayloadJson)), []byte(a.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA512, []byte(path+string("\x00")+string(PayloadJson)), []byte(a.APISecret)) headers := make(map[string]string) headers["Rest-Key"] = a.APIKey - headers["Rest-Sign"] = Base64Encode([]byte(hmac)) + headers["Rest-Sign"] = common.Base64Encode([]byte(hmac)) headers["Content-Type"] = "application/json" - resp, err := SendHTTPRequest("POST", ANX_API_URL+path, headers, bytes.NewBuffer(PayloadJson)) + resp, err := common.SendHTTPRequest("POST", ANX_API_URL+path, headers, bytes.NewBuffer(PayloadJson)) if a.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/bitfinexhttp.go b/bitfinexhttp.go index 1ffffe38..5c3c3900 100644 --- a/bitfinexhttp.go +++ b/bitfinexhttp.go @@ -10,6 +10,7 @@ import ( "time" "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -206,9 +207,9 @@ func (b *Bitfinex) Setup(exch Exchanges) { b.RESTPollingDelay = exch.RESTPollingDelay b.Verbose = exch.Verbose b.Websocket = exch.Websocket - b.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - b.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - b.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + b.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + b.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + b.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -235,7 +236,7 @@ func (b *Bitfinex) SetAPIKeys(apiKey, apiSecret string) { func (b *Bitfinex) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), IsEnabled(b.Websocket)) + log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket)) log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } @@ -248,15 +249,15 @@ func (b *Bitfinex) Run() { if err != nil { log.Printf("%s Failed to get available symbols.\n", b.GetName()) } else { - exchangeProducts = SplitStrings(StringToUpper(JoinStrings(exchangeProducts, ",")), ",") - diff := StringSliceDifference(b.AvailablePairs, exchangeProducts) + exchangeProducts = common.SplitStrings(common.StringToUpper(common.JoinStrings(exchangeProducts, ",")), ",") + diff := common.StringSliceDifference(b.AvailablePairs, exchangeProducts) if len(diff) > 0 { exch, err := GetExchangeConfig(b.Name) if err != nil { log.Println(err) } else { log.Printf("%s Updating available pairs. Difference: %s.\n", b.Name, diff) - exch.AvailablePairs = JoinStrings(exchangeProducts, ",") + exch.AvailablePairs = common.JoinStrings(exchangeProducts, ",") UpdateExchangeConfig(exch) } } @@ -279,9 +280,9 @@ func (b *Bitfinex) Run() { } func (b *Bitfinex) GetTicker(symbol string, values url.Values) (BitfinexTicker, error) { - path := EncodeURLValues(BITFINEX_API_URL+BITFINEX_TICKER+symbol, values) + path := common.EncodeURLValues(BITFINEX_API_URL+BITFINEX_TICKER+symbol, values) response := BitfinexTicker{} - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return response, err } @@ -327,7 +328,7 @@ type BitfinexLendbook struct { func (b *Bitfinex) GetStats(symbol string) (BitfinexStats, error) { response := BitfinexStats{} - err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_STATS+symbol, true, &response) + err := common.SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_STATS+symbol, true, &response) if err != nil { return response, err } @@ -335,9 +336,9 @@ func (b *Bitfinex) GetStats(symbol string) (BitfinexStats, error) { } func (b *Bitfinex) GetLendbook(symbol string, values url.Values) (BitfinexLendbook, error) { - path := EncodeURLValues(BITFINEX_API_URL+BITFINEX_LENDBOOK+symbol, values) + path := common.EncodeURLValues(BITFINEX_API_URL+BITFINEX_LENDBOOK+symbol, values) response := BitfinexLendbook{} - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return response, err } @@ -345,9 +346,9 @@ func (b *Bitfinex) GetLendbook(symbol string, values url.Values) (BitfinexLendbo } func (b *Bitfinex) GetOrderbook(symbol string, values url.Values) (BitfinexOrderbook, error) { - path := EncodeURLValues(BITFINEX_API_URL+BITFINEX_ORDERBOOK+symbol, values) + path := common.EncodeURLValues(BITFINEX_API_URL+BITFINEX_ORDERBOOK+symbol, values) response := BitfinexOrderbook{} - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return response, err } @@ -355,9 +356,9 @@ func (b *Bitfinex) GetOrderbook(symbol string, values url.Values) (BitfinexOrder } func (b *Bitfinex) GetTrades(symbol string, values url.Values) ([]BitfinexTradeStructure, error) { - path := EncodeURLValues(BITFINEX_API_URL+BITFINEX_TRADES+symbol, values) + path := common.EncodeURLValues(BITFINEX_API_URL+BITFINEX_TRADES+symbol, values) response := []BitfinexTradeStructure{} - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return nil, err } @@ -372,9 +373,9 @@ type BitfinexLends struct { } func (b *Bitfinex) GetLends(symbol string, values url.Values) ([]BitfinexLends, error) { - path := EncodeURLValues(BITFINEX_API_URL+BITFINEX_LENDS+symbol, values) + path := common.EncodeURLValues(BITFINEX_API_URL+BITFINEX_LENDS+symbol, values) response := []BitfinexLends{} - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return nil, err } @@ -383,7 +384,7 @@ func (b *Bitfinex) GetLends(symbol string, values url.Values) ([]BitfinexLends, func (b *Bitfinex) GetSymbols() ([]string, error) { products := []string{} - err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_SYMBOLS, true, &products) + err := common.SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_SYMBOLS, true, &products) if err != nil { return nil, err } @@ -392,7 +393,7 @@ func (b *Bitfinex) GetSymbols() ([]string, error) { func (b *Bitfinex) GetSymbolsDetails() ([]BitfinexSymbolDetails, error) { response := []BitfinexSymbolDetails{} - err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_SYMBOLS_DETAILS, true, &response) + err := common.SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_SYMBOLS_DETAILS, true, &response) if err != nil { return nil, err } @@ -951,7 +952,7 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ } } - PayloadJson, err := JSONEncode(request) + PayloadJson, err := common.JSONEncode(request) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") @@ -961,20 +962,20 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ log.Printf("Request JSON: %s\n", PayloadJson) } - PayloadBase64 := Base64Encode(PayloadJson) - hmac := GetHMAC(HASH_SHA512_384, []byte(PayloadBase64), []byte(b.APISecret)) + PayloadBase64 := common.Base64Encode(PayloadJson) + hmac := common.GetHMAC(common.HASH_SHA512_384, []byte(PayloadBase64), []byte(b.APISecret)) headers := make(map[string]string) headers["X-BFX-APIKEY"] = b.APIKey headers["X-BFX-PAYLOAD"] = PayloadBase64 - headers["X-BFX-SIGNATURE"] = HexEncodeToString(hmac) + headers["X-BFX-SIGNATURE"] = common.HexEncodeToString(hmac) - resp, err := SendHTTPRequest(method, BITFINEX_API_URL+path, headers, strings.NewReader("")) + resp, err := common.SendHTTPRequest(method, BITFINEX_API_URL+path, headers, strings.NewReader("")) if b.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/bitfinexwebsocket.go b/bitfinexwebsocket.go index 62606d62..5a6c2ab4 100644 --- a/bitfinexwebsocket.go +++ b/bitfinexwebsocket.go @@ -1,12 +1,14 @@ package main import ( - "github.com/gorilla/websocket" "log" "net/http" "reflect" "strconv" "time" + + "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -100,7 +102,7 @@ func (b *Bitfinex) WebsocketPingHandler() error { } func (b *Bitfinex) WebsocketSend(data interface{}) error { - json, err := JSONEncode(data) + json, err := common.JSONEncode(data) if err != nil { return err } @@ -132,7 +134,7 @@ func (b *Bitfinex) WebsocketSendAuth() error { payload := "AUTH" + strconv.FormatInt(time.Now().UnixNano(), 10)[:13] request["event"] = "auth" request["apiKey"] = b.APIKey - request["authSig"] = HexEncodeToString(GetHMAC(HASH_SHA512_384, []byte(payload), []byte(b.APISecret))) + request["authSig"] = common.HexEncodeToString(common.GetHMAC(common.HASH_SHA512_384, []byte(payload), []byte(b.APISecret))) request["authPayload"] = payload return b.WebsocketSend(request) } @@ -176,7 +178,7 @@ func (b *Bitfinex) WebsocketClient() { } hs := WebsocketHandshake{} - err = JSONDecode(resp, &hs) + err = common.JSONDecode(resp, &hs) if err != nil { log.Println(err) continue @@ -216,7 +218,7 @@ func (b *Bitfinex) WebsocketClient() { switch msgType { case websocket.TextMessage: var result interface{} - err := JSONDecode(resp, &result) + err := common.JSONDecode(resp, &result) if err != nil { log.Println(err) continue diff --git a/bitstamphttp.go b/bitstamphttp.go index cb41d9f3..888a3311 100644 --- a/bitstamphttp.go +++ b/bitstamphttp.go @@ -9,6 +9,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -189,9 +191,9 @@ func (b *Bitstamp) Setup(exch Exchanges) { b.RESTPollingDelay = exch.RESTPollingDelay b.Verbose = exch.Verbose b.Websocket = exch.Websocket - b.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - b.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - b.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + b.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + b.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + b.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -232,7 +234,7 @@ func (b *Bitstamp) SetAPIKeys(clientID, apiKey, apiSecret string) { func (b *Bitstamp) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), IsEnabled(b.Websocket)) + log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket)) log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } @@ -264,10 +266,10 @@ func (b *Bitstamp) GetTicker(currency string, hourly bool) (BitstampTicker, erro tickerEndpoint = BITSTAMP_API_TICKER_HOURLY } - path := fmt.Sprintf("%s/v%s/%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, tickerEndpoint, StringToLower(currency)) + path := fmt.Sprintf("%s/v%s/%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, tickerEndpoint, common.StringToLower(currency)) ticker := BitstampTicker{} - err := SendHTTPGetRequest(path, true, &ticker) + err := common.SendHTTPGetRequest(path, true, &ticker) if err != nil { return ticker, err @@ -309,8 +311,8 @@ func (b *Bitstamp) GetOrderbook(currency string) (BitstampOrderbook, error) { } resp := response{} - path := fmt.Sprintf("%s/v%s/%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, BITSTAMP_API_ORDERBOOK, StringToLower(currency)) - err := SendHTTPGetRequest(path, true, &resp) + path := fmt.Sprintf("%s/v%s/%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, BITSTAMP_API_ORDERBOOK, common.StringToLower(currency)) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return BitstampOrderbook{}, err } @@ -350,9 +352,9 @@ func (b *Bitstamp) GetOrderbook(currency string) (BitstampOrderbook, error) { } func (b *Bitstamp) GetTransactions(currency string, values url.Values) ([]BitstampTransactions, error) { - path := EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, BITSTAMP_API_TRANSACTIONS, StringToLower(currency)), values) + path := common.EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, BITSTAMP_API_TRANSACTIONS, common.StringToLower(currency)), values) transactions := []BitstampTransactions{} - err := SendHTTPGetRequest(path, true, &transactions) + err := common.SendHTTPGetRequest(path, true, &transactions) if err != nil { return nil, err } @@ -362,7 +364,7 @@ func (b *Bitstamp) GetTransactions(currency string, values url.Values) ([]Bitsta func (b *Bitstamp) GetEURUSDConversionRate() (BitstampEURUSDConversionRate, error) { rate := BitstampEURUSDConversionRate{} path := fmt.Sprintf("%s/%s", BITSTAMP_API_URL, BITSTAMP_API_EURUSD) - err := SendHTTPGetRequest(path, true, &rate) + err := common.SendHTTPGetRequest(path, true, &rate) if err != nil { return rate, err @@ -468,7 +470,7 @@ func (b *Bitstamp) GetUserTransactions(values url.Values) ([]BitstampUserTransac func (b *Bitstamp) GetOpenOrders(currency string) ([]BitstampOrder, error) { resp := []BitstampOrder{} - path := fmt.Sprintf("%s/%s", BITSTAMP_API_OPEN_ORDERS, StringToLower(currency)) + path := fmt.Sprintf("%s/%s", BITSTAMP_API_OPEN_ORDERS, common.StringToLower(currency)) err := b.SendAuthenticatedHTTPRequest(path, true, nil, &resp) if err != nil { @@ -529,10 +531,10 @@ func (b *Bitstamp) PlaceOrder(currency string, price float64, amount float64, bu orderType = BITSTAMP_API_SELL } - path = fmt.Sprintf("%s/%s", orderType, StringToLower(currency)) + path = fmt.Sprintf("%s/%s", orderType, common.StringToLower(currency)) if market { - path = fmt.Sprintf("%s/%s/%s", orderType, BITSTAMP_API_MARKET, StringToLower(currency)) + path = fmt.Sprintf("%s/%s/%s", orderType, BITSTAMP_API_MARKET, common.StringToLower(currency)) } err := b.SendAuthenticatedHTTPRequest(path, true, req, &response) @@ -693,8 +695,8 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, v2 bool, values url values.Set("key", b.APIKey) values.Set("nonce", nonce) - hmac := GetHMAC(HASH_SHA256, []byte(nonce+b.ClientID+b.APIKey), []byte(b.APISecret)) - values.Set("signature", strings.ToUpper(HexEncodeToString(hmac))) + hmac := common.GetHMAC(common.HASH_SHA256, []byte(nonce+b.ClientID+b.APIKey), []byte(b.APISecret)) + values.Set("signature", common.StringToUpper(common.HexEncodeToString(hmac))) if v2 { path = fmt.Sprintf("%s/v%s/%s/", BITSTAMP_API_URL, BITSTAMP_API_VERSION, path) @@ -709,7 +711,7 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, v2 bool, values url headers := make(map[string]string) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", path, headers, strings.NewReader(values.Encode())) + resp, err := common.SendHTTPRequest("POST", path, headers, strings.NewReader(values.Encode())) if err != nil { return err } @@ -718,7 +720,7 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, v2 bool, values url log.Printf("Recieved raw: %s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/bitstampwebsocket.go b/bitstampwebsocket.go index 40660569..5e073e3f 100644 --- a/bitstampwebsocket.go +++ b/bitstampwebsocket.go @@ -1,8 +1,10 @@ package main import ( - "github.com/toorop/go-pusher" "log" + + "github.com/thrasher-/gocryptotrader/common" + "github.com/toorop/go-pusher" ) type BitstampPusherOrderbook struct { @@ -54,13 +56,13 @@ func (b *Bitstamp) PusherClient() { select { case data := <-dataChannelTrade: result := BitstampPusherOrderbook{} - err := JSONDecode([]byte(data.Data), &result) + err := common.JSONDecode([]byte(data.Data), &result) if err != nil { log.Println(err) } case trade := <-tradeChannelTrade: result := BitstampPusherTrade{} - err := JSONDecode([]byte(trade.Data), &result) + err := common.JSONDecode([]byte(trade.Data), &result) if err != nil { log.Println(err) } diff --git a/btcchttp.go b/btcchttp.go index 4d4b88a5..01882b82 100644 --- a/btcchttp.go +++ b/btcchttp.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -192,9 +194,9 @@ func (b *BTCC) Setup(exch Exchanges) { b.RESTPollingDelay = exch.RESTPollingDelay b.Verbose = exch.Verbose b.Websocket = exch.Websocket - b.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - b.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - b.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + b.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + b.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + b.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -230,7 +232,7 @@ func (b *BTCC) GetFee() float64 { func (b *BTCC) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), IsEnabled(b.Websocket)) + log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket)) log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } @@ -243,7 +245,7 @@ func (b *BTCC) Run() { for _, x := range b.EnabledPairs { currency := x go func() { - ticker, err := b.GetTickerPrice(StringToLower(currency)) + ticker, err := b.GetTickerPrice(common.StringToLower(currency)) if err != nil { log.Println(err) return @@ -263,7 +265,7 @@ func (b *BTCC) GetTicker(symbol string) (BTCCTicker, error) { resp := Response{} req := fmt.Sprintf("%sdata/ticker?market=%s", BTCC_API_URL, symbol) - err := SendHTTPGetRequest(req, true, &resp) + err := common.SendHTTPGetRequest(req, true, &resp) if err != nil { return BTCCTicker{}, err } @@ -293,7 +295,7 @@ func (b *BTCC) GetTickerPrice(currency string) (TickerPrice, error) { func (b *BTCC) GetTradesLast24h(symbol string) bool { req := fmt.Sprintf("%sdata/trades?market=%s", BTCC_API_URL, symbol) - err := SendHTTPGetRequest(req, true, nil) + err := common.SendHTTPGetRequest(req, true, nil) if err != nil { log.Println(err) return false @@ -315,8 +317,8 @@ func (b *BTCC) GetTradeHistory(symbol string, limit, sinceTid int64, time time.T v.Set("sincetype", strconv.FormatInt(time.Unix(), 10)) } - req = EncodeURLValues(req, v) - err := SendHTTPGetRequest(req, true, nil) + req = common.EncodeURLValues(req, v) + err := common.SendHTTPGetRequest(req, true, nil) if err != nil { log.Println(err) return false @@ -326,7 +328,7 @@ func (b *BTCC) GetTradeHistory(symbol string, limit, sinceTid int64, time time.T func (b *BTCC) GetOrderBook(symbol string, limit int) bool { req := fmt.Sprintf("%sdata/orderbook?market=%s&limit=%d", BTCC_API_URL, symbol, limit) - err := SendHTTPGetRequest(req, true, nil) + err := common.SendHTTPGetRequest(req, true, nil) if err != nil { log.Println(err) return false @@ -760,19 +762,19 @@ func (b *BTCC) SendAuthenticatedHTTPRequest(method string, params []interface{}) } } } - encoded += JoinStrings(items, ",") + encoded += common.JoinStrings(items, ",") } if b.Verbose { log.Println(encoded) } - hmac := GetHMAC(HASH_SHA1, []byte(encoded), []byte(b.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA1, []byte(encoded), []byte(b.APISecret)) postData := make(map[string]interface{}) postData["method"] = method postData["params"] = params postData["id"] = 1 apiURL := BTCC_API_URL + BTCC_API_AUTHENTICATED_METHOD - data, err := JSONEncode(postData) + data, err := common.JSONEncode(postData) if err != nil { return errors.New("Unable to JSON Marshal POST data") @@ -784,10 +786,10 @@ func (b *BTCC) SendAuthenticatedHTTPRequest(method string, params []interface{}) headers := make(map[string]string) headers["Content-type"] = "application/json-rpc" - headers["Authorization"] = "Basic " + Base64Encode([]byte(b.APIKey+":"+HexEncodeToString(hmac))) + headers["Authorization"] = "Basic " + common.Base64Encode([]byte(b.APIKey+":"+common.HexEncodeToString(hmac))) headers["Json-Rpc-Tonce"] = nonce - resp, err := SendHTTPRequest("POST", apiURL, headers, strings.NewReader(string(data))) + resp, err := common.SendHTTPRequest("POST", apiURL, headers, strings.NewReader(string(data))) if err != nil { return err diff --git a/btccwebsocket.go b/btccwebsocket.go index e1d69f73..8226ca83 100644 --- a/btccwebsocket.go +++ b/btccwebsocket.go @@ -2,8 +2,10 @@ package main import ( "fmt" - "github.com/thrasher-/socketio" "log" + + "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/socketio" ) const ( @@ -54,7 +56,7 @@ func (b *BTCC) OnConnect(output chan socketio.Message) { currencies := []string{} for _, x := range b.EnabledPairs { - currency := StringToLower(x[3:] + x[0:3]) + currency := common.StringToLower(x[3:] + x[0:3]) currencies = append(currencies, currency) } endpoints := []string{"marketdata", "grouporder"} @@ -92,7 +94,7 @@ func (b *BTCC) OnTicker(message []byte, output chan socketio.Message) { Ticker BTCCWebsocketTicker `json:"ticker"` } var resp Response - err := JSONDecode(message, &resp) + err := common.JSONDecode(message, &resp) if err != nil { log.Println(err) @@ -105,7 +107,7 @@ func (b *BTCC) OnGroupOrder(message []byte, output chan socketio.Message) { GroupOrder BTCCWebsocketGroupOrder `json:"grouporder"` } var resp Response - err := JSONDecode(message, &resp) + err := common.JSONDecode(message, &resp) if err != nil { log.Println(err) @@ -115,7 +117,7 @@ func (b *BTCC) OnGroupOrder(message []byte, output chan socketio.Message) { func (b *BTCC) OnTrade(message []byte, output chan socketio.Message) { trade := BTCCWebsocketTrade{} - err := JSONDecode(message, &trade) + err := common.JSONDecode(message, &trade) if err != nil { log.Println(err) diff --git a/btcehttp.go b/btcehttp.go index 559534dd..dabf43e7 100644 --- a/btcehttp.go +++ b/btcehttp.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -109,9 +111,9 @@ func (b *BTCE) Setup(exch Exchanges) { b.RESTPollingDelay = exch.RESTPollingDelay b.Verbose = exch.Verbose b.Websocket = exch.Websocket - b.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - b.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - b.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + b.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + b.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + b.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -135,17 +137,17 @@ func (b *BTCE) GetFee() float64 { func (b *BTCE) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), IsEnabled(b.Websocket)) + log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket)) log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } pairs := []string{} for _, x := range b.EnabledPairs { - x = StringToLower(x[0:3] + "_" + x[3:6]) + x = common.StringToLower(x[0:3] + "_" + x[3:6]) pairs = append(pairs, x) } - pairsString := JoinStrings(pairs, "-") + pairsString := common.JoinStrings(pairs, "-") for b.Enabled { go func() { @@ -155,10 +157,10 @@ func (b *BTCE) Run() { return } for x, y := range ticker { - x = StringToUpper(x[0:3] + x[4:]) + x = common.StringToUpper(x[0:3] + x[4:]) log.Printf("BTC-e %s: Last %f High %f Low %f Volume %f\n", x, y.Last, y.High, y.Low, y.Vol_cur) b.Ticker[x] = y - AddExchangeInfo(b.GetName(), StringToUpper(x[0:3]), StringToUpper(x[4:]), y.Last, y.Vol_cur) + AddExchangeInfo(b.GetName(), common.StringToUpper(x[0:3]), common.StringToUpper(x[4:]), y.Last, y.Vol_cur) } }() time.Sleep(time.Second * b.RESTPollingDelay) @@ -182,7 +184,7 @@ type BTCEInfo struct { func (b *BTCE) GetInfo() (BTCEInfo, error) { req := fmt.Sprintf("%s/%s/%s/", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_INFO) resp := BTCEInfo{} - err := SendHTTPGetRequest(req, true, &resp) + err := common.SendHTTPGetRequest(req, true, &resp) if err != nil { return resp, err @@ -198,7 +200,7 @@ func (b *BTCE) GetTicker(symbol string) (map[string]BTCeTicker, error) { response := Response{} req := fmt.Sprintf("%s/%s/%s/%s", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_TICKER, symbol) - err := SendHTTPGetRequest(req, true, &response.Data) + err := common.SendHTTPGetRequest(req, true, &response.Data) if err != nil { return nil, err @@ -233,7 +235,7 @@ func (b *BTCE) GetDepth(symbol string) (BTCEOrderbook, error) { response := Response{} req := fmt.Sprintf("%s/%s/%s/%s", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_DEPTH, symbol) - err := SendHTTPGetRequest(req, true, &response.Data) + err := common.SendHTTPGetRequest(req, true, &response.Data) if err != nil { return BTCEOrderbook{}, err } @@ -250,7 +252,7 @@ func (b *BTCE) GetTrades(symbol string) ([]BTCETrades, error) { response := Response{} req := fmt.Sprintf("%s/%s/%s/%s", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_TRADES, symbol) - err := SendHTTPGetRequest(req, true, &response.Data) + err := common.SendHTTPGetRequest(req, true, &response.Data) if err != nil { return []BTCETrades{}, err } @@ -293,7 +295,7 @@ func (e *BTCE) GetExchangeAccountInfo() (ExchangeAccountInfo, error) { for x, y := range accountBalance.Funds { var exchangeCurrency ExchangeAccountCurrencyInfo - exchangeCurrency.CurrencyName = StringToUpper(x) + exchangeCurrency.CurrencyName = common.StringToUpper(x) exchangeCurrency.TotalValue = y exchangeCurrency.Hold = 0 response.Currencies = append(response.Currencies, exchangeCurrency) @@ -525,7 +527,7 @@ func (b *BTCE) SendAuthenticatedHTTPRequest(method string, values url.Values, re values.Set("method", method) encoded := values.Encode() - hmac := GetHMAC(HASH_SHA512, []byte(encoded), []byte(b.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA512, []byte(encoded), []byte(b.APISecret)) if b.Verbose { log.Printf("Sending POST request to %s calling method %s with params %s\n", BTCE_API_PRIVATE_URL, method, encoded) @@ -533,17 +535,17 @@ func (b *BTCE) SendAuthenticatedHTTPRequest(method string, values url.Values, re headers := make(map[string]string) headers["Key"] = b.APIKey - headers["Sign"] = HexEncodeToString(hmac) + headers["Sign"] = common.HexEncodeToString(hmac) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", BTCE_API_PRIVATE_URL, headers, strings.NewReader(encoded)) + resp, err := common.SendHTTPRequest("POST", BTCE_API_PRIVATE_URL, headers, strings.NewReader(encoded)) if err != nil { return err } response := BTCEResponse{} - err = JSONDecode([]byte(resp), &response) + err = common.JSONDecode([]byte(resp), &response) if err != nil { return err @@ -553,13 +555,13 @@ func (b *BTCE) SendAuthenticatedHTTPRequest(method string, values url.Values, re return errors.New(response.Error) } - jsonEncoded, err := JSONEncode(response.Return) + JSONEncoded, err := common.JSONEncode(response.Return) if err != nil { return err } - err = JSONDecode(jsonEncoded, &result) + err = common.JSONDecode(JSONEncoded, &result) if err != nil { return err diff --git a/btcmarkets.go b/btcmarkets.go index ad9483a0..84817982 100644 --- a/btcmarkets.go +++ b/btcmarkets.go @@ -8,6 +8,8 @@ import ( "net/url" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -118,9 +120,9 @@ func (b *BTCMarkets) Setup(exch Exchanges) { b.RESTPollingDelay = exch.RESTPollingDelay b.Verbose = exch.Verbose b.Websocket = exch.Websocket - b.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - b.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - b.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + b.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + b.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + b.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -139,7 +141,7 @@ func (b *BTCMarkets) SetAPIKeys(apiKey, apiSecret string) { } b.APIKey = apiKey - result, err := Base64Decode(apiSecret) + result, err := common.Base64Decode(apiSecret) if err != nil { log.Printf("%s unable to decode secret key.\n", b.GetName()) @@ -183,7 +185,7 @@ func (b *BTCMarkets) Run() { func (b *BTCMarkets) GetTicker(symbol string) (BTCMarketsTicker, error) { ticker := BTCMarketsTicker{} path := fmt.Sprintf("/market/%s/AUD/tick", symbol) - err := SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &ticker) + err := common.SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &ticker) if err != nil { return BTCMarketsTicker{}, err } @@ -214,7 +216,7 @@ func (b *BTCMarkets) GetTickerPrice(currency string) (TickerPrice, error) { func (b *BTCMarkets) GetOrderbook(symbol string) (BTCMarketsOrderbook, error) { orderbook := BTCMarketsOrderbook{} path := fmt.Sprintf("/market/%s/AUD/orderbook", symbol) - err := SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &orderbook) + err := common.SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &orderbook) if err != nil { return BTCMarketsOrderbook{}, err } @@ -223,8 +225,8 @@ func (b *BTCMarkets) GetOrderbook(symbol string) (BTCMarketsOrderbook, error) { func (b *BTCMarkets) GetTrades(symbol string, values url.Values) ([]BTCMarketsTrade, error) { trades := []BTCMarketsTrade{} - path := EncodeURLValues(fmt.Sprintf("%s/market/%s/AUD/trades", BTCMARKETS_API_URL, symbol), values) - err := SendHTTPGetRequest(path, true, &trades) + path := common.EncodeURLValues(fmt.Sprintf("%s/market/%s/AUD/trades", BTCMARKETS_API_URL, symbol), values) + err := common.SendHTTPGetRequest(path, true, &trades) if err != nil { return nil, err } @@ -244,8 +246,8 @@ func (b *BTCMarkets) Order(currency, instrument string, price, amount int64, ord order := Order{} order.Currency = currency order.Instrument = instrument - order.Price = price * SATOSHIS_PER_BTC - order.Volume = amount * SATOSHIS_PER_BTC + order.Price = price * common.SATOSHIS_PER_BTC + order.Volume = amount * common.SATOSHIS_PER_BTC order.OrderSide = orderSide order.OrderType = orderType order.ClientRequestId = clientReq @@ -351,14 +353,14 @@ func (b *BTCMarkets) GetOrders(currency, instrument string, limit, since int64, } for i := range resp.Orders { - resp.Orders[i].Price = resp.Orders[i].Price / SATOSHIS_PER_BTC - resp.Orders[i].OpenVolume = resp.Orders[i].OpenVolume / SATOSHIS_PER_BTC - resp.Orders[i].Volume = resp.Orders[i].Volume / SATOSHIS_PER_BTC + resp.Orders[i].Price = resp.Orders[i].Price / common.SATOSHIS_PER_BTC + resp.Orders[i].OpenVolume = resp.Orders[i].OpenVolume / common.SATOSHIS_PER_BTC + resp.Orders[i].Volume = resp.Orders[i].Volume / common.SATOSHIS_PER_BTC for x := range resp.Orders[i].Trades { - resp.Orders[i].Trades[x].Fee = resp.Orders[i].Trades[x].Fee / SATOSHIS_PER_BTC - resp.Orders[i].Trades[x].Price = resp.Orders[i].Trades[x].Price / SATOSHIS_PER_BTC - resp.Orders[i].Trades[x].Volume = resp.Orders[i].Trades[x].Volume / SATOSHIS_PER_BTC + resp.Orders[i].Trades[x].Fee = resp.Orders[i].Trades[x].Fee / common.SATOSHIS_PER_BTC + resp.Orders[i].Trades[x].Price = resp.Orders[i].Trades[x].Price / common.SATOSHIS_PER_BTC + resp.Orders[i].Trades[x].Volume = resp.Orders[i].Trades[x].Volume / common.SATOSHIS_PER_BTC } } return resp.Orders, nil @@ -390,14 +392,14 @@ func (b *BTCMarkets) GetOrderDetail(orderID []int64) ([]BTCMarketsOrder, error) } for i := range resp.Orders { - resp.Orders[i].Price = resp.Orders[i].Price / SATOSHIS_PER_BTC - resp.Orders[i].OpenVolume = resp.Orders[i].OpenVolume / SATOSHIS_PER_BTC - resp.Orders[i].Volume = resp.Orders[i].Volume / SATOSHIS_PER_BTC + resp.Orders[i].Price = resp.Orders[i].Price / common.SATOSHIS_PER_BTC + resp.Orders[i].OpenVolume = resp.Orders[i].OpenVolume / common.SATOSHIS_PER_BTC + resp.Orders[i].Volume = resp.Orders[i].Volume / common.SATOSHIS_PER_BTC for x := range resp.Orders[i].Trades { - resp.Orders[i].Trades[x].Fee = resp.Orders[i].Trades[x].Fee / SATOSHIS_PER_BTC - resp.Orders[i].Trades[x].Price = resp.Orders[i].Trades[x].Price / SATOSHIS_PER_BTC - resp.Orders[i].Trades[x].Volume = resp.Orders[i].Trades[x].Volume / SATOSHIS_PER_BTC + resp.Orders[i].Trades[x].Fee = resp.Orders[i].Trades[x].Fee / common.SATOSHIS_PER_BTC + resp.Orders[i].Trades[x].Price = resp.Orders[i].Trades[x].Price / common.SATOSHIS_PER_BTC + resp.Orders[i].Trades[x].Volume = resp.Orders[i].Trades[x].Volume / common.SATOSHIS_PER_BTC } } return resp.Orders, nil @@ -419,8 +421,8 @@ func (b *BTCMarkets) GetAccountBalance() ([]BTCMarketsAccountBalance, error) { for i := range balance { if balance[i].Currency == "LTC" || balance[i].Currency == "BTC" { - balance[i].Balance = balance[i].Balance / SATOSHIS_PER_BTC - balance[i].PendingFunds = balance[i].PendingFunds / SATOSHIS_PER_BTC + balance[i].Balance = balance[i].Balance / common.SATOSHIS_PER_BTC + balance[i].PendingFunds = balance[i].PendingFunds / common.SATOSHIS_PER_BTC } } return balance, nil @@ -451,7 +453,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa payload := []byte("") if data != nil { - payload, err = JSONEncode(data) + payload, err = common.JSONEncode(data) if err != nil { return err } @@ -460,7 +462,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa request = path + "\n" + nonce + "\n" } - hmac := GetHMAC(HASH_SHA512, []byte(request), []byte(b.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA512, []byte(request), []byte(b.APISecret)) if b.Verbose { log.Printf("Sending %s request to URL %s with params %s\n", reqType, BTCMARKETS_API_URL+path, request) @@ -472,9 +474,9 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa headers["Content-Type"] = "application/json" headers["apikey"] = b.APIKey headers["timestamp"] = nonce - headers["signature"] = Base64Encode(hmac) + headers["signature"] = common.Base64Encode(hmac) - resp, err := SendHTTPRequest(reqType, BTCMARKETS_API_URL+path, headers, bytes.NewBuffer(payload)) + resp, err := common.SendHTTPRequest(reqType, BTCMARKETS_API_URL+path, headers, bytes.NewBuffer(payload)) if err != nil { return err @@ -484,7 +486,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa log.Printf("Recieved raw: %s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return err diff --git a/common.go b/common/common.go similarity index 99% rename from common.go rename to common/common.go index 0c8a2b1b..342ee165 100644 --- a/common.go +++ b/common/common.go @@ -1,4 +1,4 @@ -package main +package common import ( "crypto/hmac" diff --git a/common_test.go b/common/common_test.go similarity index 99% rename from common_test.go rename to common/common_test.go index e4309b99..9d4fd4c8 100644 --- a/common_test.go +++ b/common/common_test.go @@ -1,4 +1,4 @@ -package main +package common import ( "bytes" diff --git a/config.go b/config.go index 513424ec..a3f79ae2 100644 --- a/config.go +++ b/config.go @@ -9,6 +9,8 @@ import ( "os" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -184,11 +186,11 @@ func CheckWebserverValues() error { return errors.New(WarningWebserverCredentialValuesEmpty) } - if !StringContains(bot.config.Webserver.ListenAddress, ":") { + if !common.StringContains(bot.config.Webserver.ListenAddress, ":") { return errors.New(WarningWebserverListenAddressInvalid) } - portStr := SplitStrings(bot.config.Webserver.ListenAddress, ":")[1] + portStr := common.SplitStrings(bot.config.Webserver.ListenAddress, ":")[1] port, err := strconv.Atoi(portStr) if err != nil { return errors.New(WarningWebserverListenAddressInvalid) diff --git a/config_encryption.go b/config_encryption.go index 015067c7..c9383fe1 100644 --- a/config_encryption.go +++ b/config_encryption.go @@ -9,6 +9,8 @@ import ( "fmt" "io" "log" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -24,7 +26,7 @@ func PromptForConfigEncryption() bool { return false } - if !YesOrNo(input) { + if !common.YesOrNo(input) { bot.config.EncryptConfig = CONFIG_FILE_ENCRYPTION_DISABLED SaveConfig() return false @@ -97,7 +99,7 @@ func DecryptConfigFile(configData, key []byte) ([]byte, error) { } func ConfirmConfigJSON(file []byte, result interface{}) error { - return JSONDecode(file, &result) + return common.JSONDecode(file, &result) } func ConfirmECS(file []byte) bool { diff --git a/currency.go b/currency.go index 20b78bcb..29cc5646 100644 --- a/currency.go +++ b/currency.go @@ -7,6 +7,8 @@ import ( "net/url" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) type Rate struct { @@ -51,21 +53,21 @@ var ( ) func IsDefaultCurrency(currency string) bool { - return StringContains(DEFAULT_CURRENCIES, StringToUpper(currency)) + return common.StringContains(DEFAULT_CURRENCIES, common.StringToUpper(currency)) } func IsFiatCurrency(currency string) bool { - return StringContains(BaseCurrencies, StringToUpper(currency)) + return common.StringContains(BaseCurrencies, common.StringToUpper(currency)) } func IsCryptocurrency(currency string) bool { - return StringContains(bot.config.Cryptocurrencies, StringToUpper(currency)) + return common.StringContains(bot.config.Cryptocurrencies, common.StringToUpper(currency)) } func ContainsSeparator(input string) (bool, string) { separators := []string{"-", "_"} for _, x := range separators { - if StringContains(input, x) { + if common.StringContains(input, x) { return true, x } } @@ -74,7 +76,7 @@ func ContainsSeparator(input string) (bool, string) { func ContainsBaseCurrencyIndex(baseCurrencies []string, currency string) (bool, string) { for _, x := range baseCurrencies { - if StringContains(currency, x) { + if common.StringContains(currency, x) { return true, x } } @@ -83,7 +85,7 @@ func ContainsBaseCurrencyIndex(baseCurrencies []string, currency string) (bool, func ContainsBaseCurrency(baseCurrencies []string, currency string) bool { for _, x := range baseCurrencies { - if StringContains(currency, x) { + if common.StringContains(currency, x) { return true } } @@ -105,18 +107,18 @@ func CheckAndAddCurrency(input []string, check string) []string { } func RetrieveConfigCurrencyPairs() error { - cryptoCurrencies := SplitStrings(bot.config.Cryptocurrencies, ",") - fiatCurrencies := SplitStrings(DEFAULT_CURRENCIES, ",") + cryptoCurrencies := common.SplitStrings(bot.config.Cryptocurrencies, ",") + fiatCurrencies := common.SplitStrings(DEFAULT_CURRENCIES, ",") for _, exchange := range bot.config.Exchanges { if exchange.Enabled { - baseCurrencies := SplitStrings(exchange.BaseCurrencies, ",") - enabledCurrencies := SplitStrings(exchange.EnabledPairs, ",") + baseCurrencies := common.SplitStrings(exchange.BaseCurrencies, ",") + enabledCurrencies := common.SplitStrings(exchange.EnabledPairs, ",") for _, currencyPair := range enabledCurrencies { ok, separator := ContainsSeparator(currencyPair) if ok { - pair := SplitStrings(currencyPair, separator) + pair := common.SplitStrings(currencyPair, separator) for _, x := range pair { ok, _ = ContainsBaseCurrencyIndex(baseCurrencies, x) if !ok { @@ -145,9 +147,9 @@ func RetrieveConfigCurrencyPairs() error { } } - BaseCurrencies = JoinStrings(fiatCurrencies, ",") + BaseCurrencies = common.JoinStrings(fiatCurrencies, ",") BaseCurrencies = strings.Replace(BaseCurrencies, "RUR", "RUB", -1) - bot.config.Cryptocurrencies = JoinStrings(cryptoCurrencies, ",") + bot.config.Cryptocurrencies = common.JoinStrings(cryptoCurrencies, ",") err := QueryYahooCurrencyValues(BaseCurrencies) @@ -160,7 +162,7 @@ func RetrieveConfigCurrencyPairs() error { } func MakecurrencyPairs(supportedCurrencies string) string { - currencies := SplitStrings(supportedCurrencies, ",") + currencies := common.SplitStrings(supportedCurrencies, ",") pairs := []string{} count := len(currencies) for i := 0; i < count; i++ { @@ -171,12 +173,12 @@ func MakecurrencyPairs(supportedCurrencies string) string { } } } - return JoinStrings(pairs, ",") + return common.JoinStrings(pairs, ",") } func ConvertCurrency(amount float64, from, to string) (float64, error) { - currency := StringToUpper(from + to) - if StringContains(currency, "RUB") { + currency := common.StringToUpper(from + to) + if common.StringContains(currency, "RUB") { currency = strings.Replace(currency, "RUB", "RUR", -1) } for x, y := range CurrencyStore { @@ -189,21 +191,21 @@ func ConvertCurrency(amount float64, from, to string) (float64, error) { func FetchYahooCurrencyData(currencyPairs []string) error { values := url.Values{} - values.Set("q", fmt.Sprintf("SELECT * from yahoo.finance.xchange WHERE pair in (\"%s\")", JoinStrings(currencyPairs, ","))) + values.Set("q", fmt.Sprintf("SELECT * from yahoo.finance.xchange WHERE pair in (\"%s\")", common.JoinStrings(currencyPairs, ","))) values.Set("format", "json") values.Set("env", YAHOO_DATABASE) headers := make(map[string]string) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", YAHOO_YQL_URL, headers, strings.NewReader(values.Encode())) + resp, err := common.SendHTTPRequest("POST", YAHOO_YQL_URL, headers, strings.NewReader(values.Encode())) if err != nil { return err } yahooResp := YahooJSONResponse{} - err = JSONDecode([]byte(resp), &yahooResp) + err = common.JSONDecode([]byte(resp), &yahooResp) if err != nil { return err @@ -222,7 +224,7 @@ func FetchYahooCurrencyData(currencyPairs []string) error { func QueryYahooCurrencyValues(currencies string) error { CurrencyStore = make(map[string]Rate) - currencyPairs := SplitStrings(MakecurrencyPairs(currencies), ",") + currencyPairs := common.SplitStrings(MakecurrencyPairs(currencies), ",") log.Printf("%d fiat currency pairs generated. Fetching Yahoo currency data (this may take a minute)..\n", len(currencyPairs)) var err error var pairs []string diff --git a/events.go b/events.go index 3999c325..99f2196f 100644 --- a/events.go +++ b/events.go @@ -5,6 +5,8 @@ import ( "fmt" "log" "strconv" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -88,8 +90,8 @@ func GetEventCounter() (int, int) { } func (e *Event) ExecuteAction() bool { - if StringContains(e.Action, ",") { - action := SplitStrings(e.Action, ",") + if common.StringContains(e.Action, ",") { + action := common.SplitStrings(e.Action, ",") if action[0] == ACTION_SMS_NOTIFY { message := fmt.Sprintf("Event triggered: %s", e.EventToString()) if action[1] == "ALL" { @@ -105,13 +107,13 @@ func (e *Event) ExecuteAction() bool { } func (e *Event) EventToString() string { - condition := SplitStrings(e.Condition, ",") + condition := common.SplitStrings(e.Condition, ",") return fmt.Sprintf("If the %s%s %s on %s is %s then %s.", e.FirstCurrency, e.SecondCurrency, e.Item, e.Exchange, condition[0]+" "+condition[1], e.Action) } func (e *Event) CheckCondition() bool { lastPrice := 0.00 - condition := SplitStrings(e.Condition, ",") + condition := common.SplitStrings(e.Condition, ",") targetPrice, _ := strconv.ParseFloat(condition[1], 64) ticker, err := GetTickerByExchange(e.Exchange) @@ -169,18 +171,18 @@ func IsValidEvent(Exchange, Item, Condition, Action string) error { return ErrInvalidItem } - if !StringContains(Condition, ",") { + if !common.StringContains(Condition, ",") { return ErrInvalidCondition } - condition := SplitStrings(Condition, ",") + condition := common.SplitStrings(Condition, ",") if !IsValidCondition(condition[0]) || len(condition[1]) == 0 { return ErrInvalidCondition } - if StringContains(Action, ",") { - action := SplitStrings(Action, ",") + if common.StringContains(Action, ",") { + action := common.SplitStrings(Action, ",") if action[0] != ACTION_SMS_NOTIFY { return ErrInvalidAction diff --git a/gdaxhttp.go b/gdaxhttp.go index 672ecaeb..6e9014f1 100644 --- a/gdaxhttp.go +++ b/gdaxhttp.go @@ -8,6 +8,8 @@ import ( "net/url" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -153,9 +155,9 @@ func (g *GDAX) Setup(exch Exchanges) { g.RESTPollingDelay = exch.RESTPollingDelay g.Verbose = exch.Verbose g.Websocket = exch.Websocket - g.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - g.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - g.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + g.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + g.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + g.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -177,7 +179,7 @@ func (g *GDAX) GetFee(maker bool) float64 { func (g *GDAX) Run() { if g.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", g.GetName(), IsEnabled(g.Websocket), GDAX_WEBSOCKET_URL) + log.Printf("%s Websocket: %s. (url: %s).\n", g.GetName(), common.IsEnabled(g.Websocket), GDAX_WEBSOCKET_URL) log.Printf("%s polling delay: %ds.\n", g.GetName(), g.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", g.GetName(), len(g.EnabledPairs), g.EnabledPairs) } @@ -196,14 +198,14 @@ func (g *GDAX) Run() { currencies = append(currencies, x.ID[0:3]+x.ID[4:]) } } - diff := StringSliceDifference(g.AvailablePairs, currencies) + diff := common.StringSliceDifference(g.AvailablePairs, currencies) if len(diff) > 0 { exch, err := GetExchangeConfig(g.Name) if err != nil { log.Println(err) } else { log.Printf("%s Updating available pairs. Difference: %s.\n", g.Name, diff) - exch.AvailablePairs = JoinStrings(currencies, ",") + exch.AvailablePairs = common.JoinStrings(currencies, ",") UpdateExchangeConfig(exch) } } @@ -234,7 +236,7 @@ func (g *GDAX) SetAPIKeys(password, apiKey, apiSecret string) { g.Password = password g.APIKey = apiKey - result, err := Base64Decode(apiSecret) + result, err := common.Base64Decode(apiSecret) if err != nil { log.Printf("%s unable to decode secret key.", g.GetName()) @@ -247,7 +249,7 @@ func (g *GDAX) SetAPIKeys(password, apiKey, apiSecret string) { func (g *GDAX) GetProducts() ([]GDAXProduct, error) { products := []GDAXProduct{} - err := SendHTTPGetRequest(GDAX_API_URL+GDAX_PRODUCTS, true, &products) + err := common.SendHTTPGetRequest(GDAX_API_URL+GDAX_PRODUCTS, true, &products) if err != nil { return nil, err @@ -266,7 +268,7 @@ func (g *GDAX) GetOrderbook(symbol string, level int) (interface{}, error) { path = fmt.Sprintf("%s/%s/%s", GDAX_API_URL+GDAX_PRODUCTS, symbol, GDAX_ORDERBOOK) } - err := SendHTTPGetRequest(path, true, &orderbook) + err := common.SendHTTPGetRequest(path, true, &orderbook) if err != nil { return nil, err } @@ -349,7 +351,7 @@ func (g *GDAX) GetOrderbook(symbol string, level int) (interface{}, error) { func (g *GDAX) GetTicker(symbol string) (GDAXTicker, error) { ticker := GDAXTicker{} path := fmt.Sprintf("%s/%s/%s", GDAX_API_URL+GDAX_PRODUCTS, symbol, GDAX_TICKER) - err := SendHTTPGetRequest(path, true, &ticker) + err := common.SendHTTPGetRequest(path, true, &ticker) if err != nil { return ticker, err @@ -389,7 +391,7 @@ func (g *GDAX) GetTickerPrice(currency string) (TickerPrice, error) { func (g *GDAX) GetTrades(symbol string) ([]GDAXTrade, error) { trades := []GDAXTrade{} path := fmt.Sprintf("%s/%s/%s", GDAX_API_URL+GDAX_PRODUCTS, symbol, GDAX_TRADES) - err := SendHTTPGetRequest(path, true, &trades) + err := common.SendHTTPGetRequest(path, true, &trades) if err != nil { return nil, err @@ -413,8 +415,8 @@ func (g *GDAX) GetHistoricRates(symbol string, start, end, granularity int64) ([ values.Set("granularity", strconv.FormatInt(granularity, 10)) } - path := EncodeURLValues(fmt.Sprintf("%s/%s/%s", GDAX_API_URL+GDAX_PRODUCTS, symbol, GDAX_HISTORY), values) - err := SendHTTPGetRequest(path, true, &history) + path := common.EncodeURLValues(fmt.Sprintf("%s/%s/%s", GDAX_API_URL+GDAX_PRODUCTS, symbol, GDAX_HISTORY), values) + err := common.SendHTTPGetRequest(path, true, &history) if err != nil { return nil, err @@ -425,7 +427,7 @@ func (g *GDAX) GetHistoricRates(symbol string, start, end, granularity int64) ([ func (g *GDAX) GetStats(symbol string) (GDAXStats, error) { stats := GDAXStats{} path := fmt.Sprintf("%s/%s/%s", GDAX_API_URL+GDAX_PRODUCTS, symbol, GDAX_STATS) - err := SendHTTPGetRequest(path, true, &stats) + err := common.SendHTTPGetRequest(path, true, &stats) if err != nil { return stats, err @@ -435,7 +437,7 @@ func (g *GDAX) GetStats(symbol string) (GDAXStats, error) { func (g *GDAX) GetCurrencies() ([]GDAXCurrency, error) { currencies := []GDAXCurrency{} - err := SendHTTPGetRequest(GDAX_API_URL+GDAX_CURRENCIES, true, ¤cies) + err := common.SendHTTPGetRequest(GDAX_API_URL+GDAX_CURRENCIES, true, ¤cies) if err != nil { return nil, err @@ -581,7 +583,7 @@ type GDAXOrdersResponse struct { } func (g *GDAX) GetOrders(params url.Values) ([]GDAXOrdersResponse, error) { - path := EncodeURLValues(GDAX_API_URL+GDAX_ORDERS, params) + path := common.EncodeURLValues(GDAX_API_URL+GDAX_ORDERS, params) resp := []GDAXOrdersResponse{} err := g.SendAuthenticatedHTTPRequest("GET", path, nil, &resp) if err != nil { @@ -629,7 +631,7 @@ type GDAXFillResponse struct { } func (g *GDAX) GetFills(params url.Values) ([]GDAXFillResponse, error) { - path := EncodeURLValues(GDAX_API_URL+GDAX_FILLS, params) + path := common.EncodeURLValues(GDAX_API_URL+GDAX_FILLS, params) resp := []GDAXFillResponse{} err := g.SendAuthenticatedHTTPRequest("GET", path, nil, &resp) if err != nil { @@ -694,7 +696,7 @@ func (g *GDAX) SendAuthenticatedHTTPRequest(method, path string, params map[stri payload := []byte("") if params != nil { - payload, err = JSONEncode(params) + payload, err = common.JSONEncode(params) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") @@ -706,21 +708,21 @@ func (g *GDAX) SendAuthenticatedHTTPRequest(method, path string, params map[stri } message := timestamp + method + path + string(payload) - hmac := GetHMAC(HASH_SHA256, []byte(message), []byte(g.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA256, []byte(message), []byte(g.APISecret)) headers := make(map[string]string) - headers["CB-ACCESS-SIGN"] = Base64Encode([]byte(hmac)) + headers["CB-ACCESS-SIGN"] = common.Base64Encode([]byte(hmac)) headers["CB-ACCESS-TIMESTAMP"] = timestamp headers["CB-ACCESS-KEY"] = g.APIKey headers["CB-ACCESS-PASSPHRASE"] = g.Password headers["Content-Type"] = "application/json" - resp, err := SendHTTPRequest(method, GDAX_API_URL+path, headers, bytes.NewBuffer(payload)) + resp, err := common.SendHTTPRequest(method, GDAX_API_URL+path, headers, bytes.NewBuffer(payload)) if g.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/gdaxwebsocket.go b/gdaxwebsocket.go index d6cee0c2..fc9fc33e 100644 --- a/gdaxwebsocket.go +++ b/gdaxwebsocket.go @@ -1,9 +1,11 @@ package main import ( - "github.com/gorilla/websocket" "log" "net/http" + + "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -71,7 +73,7 @@ type GDAXWebsocketChange struct { func (g *GDAX) WebsocketSubscribe(product string, conn *websocket.Conn) error { subscribe := GDAXWebsocketSubscribe{"subscribe", product} - json, err := JSONEncode(subscribe) + json, err := common.JSONEncode(subscribe) if err != nil { return err } @@ -128,7 +130,7 @@ func (g *GDAX) WebsocketClient() { } msgType := MsgType{} - err := JSONDecode(resp, &msgType) + err := common.JSONDecode(resp, &msgType) if err != nil { log.Println(err) continue @@ -140,35 +142,35 @@ func (g *GDAX) WebsocketClient() { break case "received": received := GDAXWebsocketReceived{} - err := JSONDecode(resp, &received) + err := common.JSONDecode(resp, &received) if err != nil { log.Println(err) continue } case "open": open := GDAXWebsocketOpen{} - err := JSONDecode(resp, &open) + err := common.JSONDecode(resp, &open) if err != nil { log.Println(err) continue } case "done": done := GDAXWebsocketDone{} - err := JSONDecode(resp, &done) + err := common.JSONDecode(resp, &done) if err != nil { log.Println(err) continue } case "match": match := GDAXWebsocketMatch{} - err := JSONDecode(resp, &match) + err := common.JSONDecode(resp, &match) if err != nil { log.Println(err) continue } case "change": change := GDAXWebsocketChange{} - err := JSONDecode(resp, &change) + err := common.JSONDecode(resp, &change) if err != nil { log.Println(err) continue diff --git a/geminihttp.go b/geminihttp.go index abca3e3a..5aac6ffb 100644 --- a/geminihttp.go +++ b/geminihttp.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -134,9 +136,9 @@ func (g *Gemini) Setup(exch Exchanges) { g.RESTPollingDelay = exch.RESTPollingDelay g.Verbose = exch.Verbose g.Websocket = exch.Websocket - g.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - g.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - g.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + g.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + g.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + g.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -163,15 +165,15 @@ func (g *Gemini) Run() { if err != nil { log.Printf("%s Failed to get available symbols.\n", g.GetName()) } else { - exchangeProducts = SplitStrings(StringToUpper(JoinStrings(exchangeProducts, ",")), ",") - diff := StringSliceDifference(g.AvailablePairs, exchangeProducts) + exchangeProducts = common.SplitStrings(common.StringToUpper(common.JoinStrings(exchangeProducts, ",")), ",") + diff := common.StringSliceDifference(g.AvailablePairs, exchangeProducts) if len(diff) > 0 { exch, err := GetExchangeConfig(g.Name) if err != nil { log.Println(err) } else { log.Printf("%s Updating available pairs. Difference: %s.\n", g.Name, diff) - exch.AvailablePairs = JoinStrings(exchangeProducts, ",") + exch.AvailablePairs = common.JoinStrings(exchangeProducts, ",") UpdateExchangeConfig(exch) } } @@ -218,7 +220,7 @@ func (g *Gemini) GetTicker(currency string) (GeminiTicker, error) { resp := TickerResponse{} path := fmt.Sprintf("%s/v%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_TICKER, currency) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return ticker, err } @@ -261,7 +263,7 @@ func (g *Gemini) GetTickerPrice(currency string) (TickerPrice, error) { func (g *Gemini) GetSymbols() ([]string, error) { symbols := []string{} path := fmt.Sprintf("%s/v%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_SYMBOLS) - err := SendHTTPGetRequest(path, true, &symbols) + err := common.SendHTTPGetRequest(path, true, &symbols) if err != nil { return nil, err } @@ -281,7 +283,7 @@ type GeminiAuction struct { func (g *Gemini) GetAuction(currency string) (GeminiAuction, error) { path := fmt.Sprintf("%s/v%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_AUCTION, currency) auction := GeminiAuction{} - err := SendHTTPGetRequest(path, true, &auction) + err := common.SendHTTPGetRequest(path, true, &auction) if err != nil { return auction, err } @@ -302,9 +304,9 @@ type GeminiAuctionHistory struct { } func (g *Gemini) GetAuctionHistory(currency string, params url.Values) ([]GeminiAuctionHistory, error) { - path := EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_AUCTION, currency, GEMINI_AUCTION_HISTORY), params) + path := common.EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_AUCTION, currency, GEMINI_AUCTION_HISTORY), params) auctionHist := []GeminiAuctionHistory{} - err := SendHTTPGetRequest(path, true, &auctionHist) + err := common.SendHTTPGetRequest(path, true, &auctionHist) if err != nil { return nil, err } @@ -312,9 +314,9 @@ func (g *Gemini) GetAuctionHistory(currency string, params url.Values) ([]Gemini } func (g *Gemini) GetOrderbook(currency string, params url.Values) (GeminiOrderbook, error) { - path := EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_ORDERBOOK, currency), params) + path := common.EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_ORDERBOOK, currency), params) orderbook := GeminiOrderbook{} - err := SendHTTPGetRequest(path, true, &orderbook) + err := common.SendHTTPGetRequest(path, true, &orderbook) if err != nil { return GeminiOrderbook{}, err } @@ -323,9 +325,9 @@ func (g *Gemini) GetOrderbook(currency string, params url.Values) (GeminiOrderbo } func (g *Gemini) GetTrades(currency string, params url.Values) ([]GeminiTrade, error) { - path := EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_TRADES, currency), params) + path := common.EncodeURLValues(fmt.Sprintf("%s/v%s/%s/%s", GEMINI_API_URL, GEMINI_API_VERSION, GEMINI_TRADES, currency), params) trades := []GeminiTrade{} - err := SendHTTPGetRequest(path, true, &trades) + err := common.SendHTTPGetRequest(path, true, &trades) if err != nil { return []GeminiTrade{}, err } @@ -461,7 +463,7 @@ func (g *Gemini) SendAuthenticatedHTTPRequest(method, path string, params map[st } } - PayloadJson, err := JSONEncode(request) + PayloadJson, err := common.JSONEncode(request) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request") @@ -471,20 +473,20 @@ func (g *Gemini) SendAuthenticatedHTTPRequest(method, path string, params map[st log.Printf("Request JSON: %s\n", PayloadJson) } - PayloadBase64 := Base64Encode(PayloadJson) - hmac := GetHMAC(HASH_SHA512_384, []byte(PayloadBase64), []byte(g.APISecret)) + PayloadBase64 := common.Base64Encode(PayloadJson) + hmac := common.GetHMAC(common.HASH_SHA512_384, []byte(PayloadBase64), []byte(g.APISecret)) headers := make(map[string]string) headers["X-GEMINI-APIKEY"] = g.APIKey headers["X-GEMINI-PAYLOAD"] = PayloadBase64 - headers["X-GEMINI-SIGNATURE"] = HexEncodeToString(hmac) + headers["X-GEMINI-SIGNATURE"] = common.HexEncodeToString(hmac) - resp, err := SendHTTPRequest(method, BITFINEX_API_URL+path, headers, strings.NewReader("")) + resp, err := common.SendHTTPRequest(method, BITFINEX_API_URL+path, headers, strings.NewReader("")) if g.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/huobihttp.go b/huobihttp.go index 03ee2a17..8ec7802c 100644 --- a/huobihttp.go +++ b/huobihttp.go @@ -7,6 +7,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -73,9 +75,9 @@ func (h *HUOBI) Setup(exch Exchanges) { h.RESTPollingDelay = exch.RESTPollingDelay h.Verbose = exch.Verbose h.Websocket = exch.Websocket - h.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - h.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - h.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + h.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + h.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + h.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -98,7 +100,7 @@ func (h *HUOBI) GetFee() float64 { func (h *HUOBI) Run() { if h.Verbose { - log.Printf("%s Websocket: %s (url: %s).\n", h.GetName(), IsEnabled(h.Websocket), HUOBI_SOCKETIO_ADDRESS) + log.Printf("%s Websocket: %s (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket), HUOBI_SOCKETIO_ADDRESS) log.Printf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) } @@ -109,7 +111,7 @@ func (h *HUOBI) Run() { for h.Enabled { for _, x := range h.EnabledPairs { - currency := StringToLower(x[0:3]) + currency := common.StringToLower(x[0:3]) go func() { ticker, err := h.GetTickerPrice(currency) if err != nil { @@ -120,8 +122,8 @@ func (h *HUOBI) Run() { HuobiHighUSD, _ := ConvertCurrency(ticker.High, "CNY", "USD") HuobiLowUSD, _ := ConvertCurrency(ticker.Low, "CNY", "USD") log.Printf("Huobi %s: Last %f (%f) High %f (%f) Low %f (%f) Volume %f\n", currency, HuobiLastUSD, ticker.Last, HuobiHighUSD, ticker.High, HuobiLowUSD, ticker.Low, ticker.Volume) - AddExchangeInfo(h.GetName(), StringToUpper(currency[0:3]), StringToUpper(currency[3:]), ticker.Last, ticker.Volume) - AddExchangeInfo(h.GetName(), StringToUpper(currency[0:3]), "USD", HuobiLastUSD, ticker.Volume) + AddExchangeInfo(h.GetName(), common.StringToUpper(currency[0:3]), common.StringToUpper(currency[3:]), ticker.Last, ticker.Volume) + AddExchangeInfo(h.GetName(), common.StringToUpper(currency[0:3]), "USD", HuobiLastUSD, ticker.Volume) }() } time.Sleep(time.Second * h.RESTPollingDelay) @@ -131,7 +133,7 @@ func (h *HUOBI) Run() { func (h *HUOBI) GetTicker(symbol string) (HuobiTicker, error) { resp := HuobiTickerResponse{} path := fmt.Sprintf("http://api.huobi.com/staticmarket/ticker_%s_json.js", symbol) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return HuobiTicker{}, err @@ -140,7 +142,7 @@ func (h *HUOBI) GetTicker(symbol string) (HuobiTicker, error) { } func (h *HUOBI) GetTickerPrice(currency string) (TickerPrice, error) { - tickerNew, err := GetTicker(h.GetName(), StringToUpper(currency[0:3]), StringToUpper(currency[3:])) + tickerNew, err := GetTicker(h.GetName(), common.StringToUpper(currency[0:3]), common.StringToUpper(currency[3:])) if err == nil { return tickerNew, nil } @@ -152,8 +154,8 @@ func (h *HUOBI) GetTickerPrice(currency string) (TickerPrice, error) { } tickerPrice.Ask = ticker.Sell tickerPrice.Bid = ticker.Buy - tickerPrice.FirstCurrency = StringToUpper(currency[0:3]) - tickerPrice.SecondCurrency = StringToUpper(currency[3:]) + tickerPrice.FirstCurrency = common.StringToUpper(currency[0:3]) + tickerPrice.SecondCurrency = common.StringToUpper(currency[3:]) tickerPrice.CurrencyPair = tickerPrice.FirstCurrency + "_" + tickerPrice.SecondCurrency tickerPrice.Low = ticker.Low tickerPrice.Last = ticker.Last @@ -165,7 +167,7 @@ func (h *HUOBI) GetTickerPrice(currency string) (TickerPrice, error) { func (h *HUOBI) GetOrderBook(symbol string) bool { path := fmt.Sprintf("http://api.huobi.com/staticmarket/depth_%s_json.js", symbol) - err := SendHTTPGetRequest(path, true, nil) + err := common.SendHTTPGetRequest(path, true, nil) if err != nil { log.Println(err) return false @@ -281,8 +283,8 @@ func (h *HUOBI) SendAuthenticatedRequest(method string, v url.Values) error { v.Set("access_key", h.AccessKey) v.Set("created", strconv.FormatInt(time.Now().Unix(), 10)) v.Set("method", method) - hash := GetMD5([]byte(v.Encode() + "&secret_key=" + h.SecretKey)) - v.Set("sign", strings.ToLower(HexEncodeToString(hash))) + hash := common.GetMD5([]byte(v.Encode() + "&secret_key=" + h.SecretKey)) + v.Set("sign", common.StringToLower(common.HexEncodeToString(hash))) encoded := v.Encode() if h.Verbose { @@ -292,7 +294,7 @@ func (h *HUOBI) SendAuthenticatedRequest(method string, v url.Values) error { headers := make(map[string]string) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", HUOBI_API_URL, headers, strings.NewReader(encoded)) + resp, err := common.SendHTTPRequest("POST", HUOBI_API_URL, headers, strings.NewReader(encoded)) if err != nil { return err diff --git a/huobiwebsocket.go b/huobiwebsocket.go index e9e6c9ae..ef5e3bd4 100644 --- a/huobiwebsocket.go +++ b/huobiwebsocket.go @@ -1,8 +1,10 @@ package main import ( - "github.com/thrasher-/socketio" "log" + + "github.com/thrasher-/gocryptotrader/common" + "github.com/thrasher-/socketio" ) const ( @@ -164,9 +166,9 @@ func (h *HUOBI) OnConnect(output chan socketio.Message) { } for _, x := range h.EnabledPairs { - currency := StringToLower(x) + currency := common.StringToLower(x) msg := h.BuildHuobiWebsocketRequestExtra(HUOBI_SOCKET_REQ_SUBSCRIBE, 100, h.BuildHuobiWebsocketParamsList(HUOBI_SOCKET_MARKET_OVERVIEW, currency, "pushLong", "", "", "", "", "")) - result, err := JSONEncode(msg) + result, err := common.JSONEncode(msg) if err != nil { log.Println(err) } @@ -189,7 +191,7 @@ func (h *HUOBI) OnMessage(message []byte, output chan socketio.Message) { func (h *HUOBI) OnRequest(message []byte, output chan socketio.Message) { response := HuobiResponse{} - err := JSONDecode(message, &response) + err := common.JSONDecode(message, &response) if err != nil { log.Println(err) } diff --git a/itbithttp.go b/itbithttp.go index 647be14f..53f4bd6a 100644 --- a/itbithttp.go +++ b/itbithttp.go @@ -7,6 +7,8 @@ import ( "net/url" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -80,9 +82,9 @@ func (i *ItBit) Setup(exch Exchanges) { i.RESTPollingDelay = exch.RESTPollingDelay i.Verbose = exch.Verbose i.Websocket = exch.Websocket - i.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - i.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - i.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + i.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + i.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + i.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -134,7 +136,7 @@ func (i *ItBit) Run() { func (i *ItBit) GetTicker(currency string) (ItBitTicker, error) { path := ITBIT_API_URL + "/markets/" + currency + "/ticker" var itbitTicker ItBitTicker - err := SendHTTPGetRequest(path, true, &itbitTicker) + err := common.SendHTTPGetRequest(path, true, &itbitTicker) if err != nil { return ItBitTicker{}, err } @@ -182,7 +184,7 @@ type ItBitOrderbookResponse struct { func (i *ItBit) GetOrderbook(currency string) (ItBitOrderbookResponse, error) { response := ItBitOrderbookResponse{} path := ITBIT_API_URL + "/markets/" + currency + "/order_book" - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return ItBitOrderbookResponse{}, err } @@ -191,7 +193,7 @@ func (i *ItBit) GetOrderbook(currency string) (ItBitOrderbookResponse, error) { func (i *ItBit) GetTradeHistory(currency, timestamp string) bool { req := "/trades?since=" + timestamp - err := SendHTTPGetRequest(ITBIT_API_URL+"markets/"+currency+req, true, nil) + err := common.SendHTTPGetRequest(ITBIT_API_URL+"markets/"+currency+req, true, nil) if err != nil { log.Println(err) return false @@ -250,7 +252,7 @@ func (i *ItBit) GetWalletBalance(walletID, currency string) { } func (i *ItBit) GetWalletTrades(walletID string, params url.Values) { - path := EncodeURLValues("/wallets/"+walletID+"/trades", params) + path := common.EncodeURLValues("/wallets/"+walletID+"/trades", params) err := i.SendAuthenticatedHTTPRequest("GET", path, nil) if err != nil { @@ -259,7 +261,7 @@ func (i *ItBit) GetWalletTrades(walletID string, params url.Values) { } func (i *ItBit) GetWalletOrders(walletID string, params url.Values) { - path := EncodeURLValues("/wallets/"+walletID+"/orders", params) + path := common.EncodeURLValues("/wallets/"+walletID+"/orders", params) err := i.SendAuthenticatedHTTPRequest("GET", path, nil) if err != nil { @@ -368,7 +370,7 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params PayloadJson := []byte("") if params != nil { - PayloadJson, err = JSONEncode(request) + PayloadJson, err = common.JSONEncode(request) if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON Marshal request") @@ -380,15 +382,15 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params } nonceStr := strconv.Itoa(nonce) - message, err := JSONEncode([]string{method, url, string(PayloadJson), nonceStr, timestamp}) + message, err := common.JSONEncode([]string{method, url, string(PayloadJson), nonceStr, timestamp}) if err != nil { log.Println(err) return } - hash := GetSHA256([]byte(nonceStr + string(message))) - hmac := GetHMAC(HASH_SHA512, []byte(url+string(hash)), []byte(i.APISecret)) - signature := Base64Encode(hmac) + hash := common.GetSHA256([]byte(nonceStr + string(message))) + hmac := common.GetHMAC(common.HASH_SHA512, []byte(url+string(hash)), []byte(i.APISecret)) + signature := common.Base64Encode(hmac) headers := make(map[string]string) headers["Authorization"] = i.ClientKey + ":" + signature @@ -396,7 +398,7 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params headers["X-Auth-Nonce"] = nonceStr headers["Content-Type"] = "application/json" - resp, err := SendHTTPRequest(method, url, headers, bytes.NewBuffer([]byte(PayloadJson))) + resp, err := common.SendHTTPRequest(method, url, headers, bytes.NewBuffer([]byte(PayloadJson))) if i.Verbose { log.Printf("Recieved raw: \n%s\n", resp) diff --git a/kraken.go b/kraken.go index 1a167870..d5afde83 100644 --- a/kraken.go +++ b/kraken.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -84,9 +86,9 @@ func (k *Kraken) Setup(exch Exchanges) { k.RESTPollingDelay = exch.RESTPollingDelay k.Verbose = exch.Verbose k.Websocket = exch.Websocket - k.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - k.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - k.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + k.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + k.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + k.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -125,21 +127,21 @@ func (k *Kraken) Run() { for _, v := range assetPairs { exchangeProducts = append(exchangeProducts, v.Altname) } - diff := StringSliceDifference(k.AvailablePairs, exchangeProducts) + diff := common.StringSliceDifference(k.AvailablePairs, exchangeProducts) if len(diff) > 0 { exch, err := GetExchangeConfig(k.Name) if err != nil { log.Println(err) } else { log.Printf("%s Updating available pairs. Difference: %s.\n", k.Name, diff) - exch.AvailablePairs = JoinStrings(exchangeProducts, ",") + exch.AvailablePairs = common.JoinStrings(exchangeProducts, ",") UpdateExchangeConfig(exch) } } } for k.Enabled { - err := k.GetTicker(JoinStrings(k.EnabledPairs, ",")) + err := k.GetTicker(common.JoinStrings(k.EnabledPairs, ",")) if err != nil { log.Println(err) } else { @@ -156,7 +158,7 @@ func (k *Kraken) Run() { func (k *Kraken) GetServerTime() error { var result interface{} path := fmt.Sprintf("%s/%s/public/%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_SERVER_TIME) - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return err @@ -169,7 +171,7 @@ func (k *Kraken) GetServerTime() error { func (k *Kraken) GetAssets() error { var result interface{} path := fmt.Sprintf("%s/%s/public/%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_ASSETS) - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return err @@ -206,7 +208,7 @@ func (k *Kraken) GetAssetPairs() (map[string]KrakenAssetPairs, error) { response := Response{} path := fmt.Sprintf("%s/%s/public/%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_ASSET_PAIRS) - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return nil, err @@ -250,7 +252,7 @@ func (k *Kraken) GetTicker(symbol string) error { resp := Response{} path := fmt.Sprintf("%s/%s/public/%s?%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_TICKER, values.Encode()) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return err @@ -298,7 +300,7 @@ func (k *Kraken) GetOHLC(symbol string) error { var result interface{} path := fmt.Sprintf("%s/%s/public/%s?%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_OHLC, values.Encode()) - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return err @@ -314,7 +316,7 @@ func (k *Kraken) GetDepth(symbol string) error { var result interface{} path := fmt.Sprintf("%s/%s/public/%s?%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_DEPTH, values.Encode()) - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return err @@ -330,7 +332,7 @@ func (k *Kraken) GetTrades(symbol string) error { var result interface{} path := fmt.Sprintf("%s/%s/public/%s?%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_TRADES, values.Encode()) - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return err @@ -346,7 +348,7 @@ func (k *Kraken) GetSpread(symbol string) { var result interface{} path := fmt.Sprintf("%s/%s/public/%s?%s", KRAKEN_API_URL, KRAKEN_API_VERSION, KRAKEN_SPREAD, values.Encode()) - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { log.Println(err) @@ -649,14 +651,14 @@ func (k *Kraken) CancelOrder(orderID int64) { func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) (interface{}, error) { path := fmt.Sprintf("/%s/private/%s", KRAKEN_API_VERSION, method) values.Set("nonce", strconv.FormatInt(time.Now().UnixNano(), 10)) - secret, err := Base64Decode(k.APISecret) + secret, err := common.Base64Decode(k.APISecret) if err != nil { return nil, err } - shasum := GetSHA256([]byte(values.Get("nonce") + values.Encode())) - signature := Base64Encode(GetHMAC(HASH_SHA512, append([]byte(path), shasum...), secret)) + shasum := common.GetSHA256([]byte(values.Get("nonce") + values.Encode())) + signature := common.Base64Encode(common.GetHMAC(common.HASH_SHA512, append([]byte(path), shasum...), secret)) if k.Verbose { log.Printf("Sending POST request to %s, path: %s.", KRAKEN_API_URL, path) @@ -666,7 +668,7 @@ func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) headers["API-Key"] = k.ClientKey headers["API-Sign"] = signature - resp, err := SendHTTPRequest("POST", KRAKEN_API_URL+path, headers, strings.NewReader(values.Encode())) + resp, err := common.SendHTTPRequest("POST", KRAKEN_API_URL+path, headers, strings.NewReader(values.Encode())) if err != nil { return nil, err diff --git a/lakebtchttp.go b/lakebtchttp.go index d23647df..baf64a7d 100644 --- a/lakebtchttp.go +++ b/lakebtchttp.go @@ -7,6 +7,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -91,9 +93,9 @@ func (l *LakeBTC) Setup(exch Exchanges) { l.RESTPollingDelay = exch.RESTPollingDelay l.Verbose = exch.Verbose l.Websocket = exch.Websocket - l.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - l.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - l.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + l.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + l.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + l.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -151,7 +153,7 @@ type LakeBTCTickerResponse struct { func (l *LakeBTC) GetTicker() (map[string]LakeBTCTicker, error) { response := make(map[string]LakeBTCTickerResponse) path := fmt.Sprintf("%s/%s", LAKEBTC_API_URL, LAKEBTC_TICKER) - err := SendHTTPGetRequest(path, true, &response) + err := common.SendHTTPGetRequest(path, true, &response) if err != nil { return nil, err } @@ -160,7 +162,7 @@ func (l *LakeBTC) GetTicker() (map[string]LakeBTCTicker, error) { var addresses []string for k, v := range response { var ticker LakeBTCTicker - key := StringToUpper(k) + key := common.StringToUpper(k) if v.Ask != nil { ticker.Ask, _ = strconv.ParseFloat(v.Ask.(string), 64) } @@ -220,9 +222,9 @@ func (l *LakeBTC) GetOrderBook(currency string) (LakeBTCOrderbook, error) { Bids [][]string `json:"bids"` Asks [][]string `json:"asks"` } - path := fmt.Sprintf("%s/%s?symbol=%s", LAKEBTC_API_URL, LAKEBTC_ORDERBOOK, StringToLower(currency)) + path := fmt.Sprintf("%s/%s?symbol=%s", LAKEBTC_API_URL, LAKEBTC_ORDERBOOK, common.StringToLower(currency)) resp := Response{} - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return LakeBTCOrderbook{}, err } @@ -266,9 +268,9 @@ type LakeBTCTradeHistory struct { } func (l *LakeBTC) GetTradeHistory(currency string) ([]LakeBTCTradeHistory, error) { - path := fmt.Sprintf("%s/%s?symbol=%s", LAKEBTC_API_URL, LAKEBTC_TRADES, StringToLower(currency)) + path := fmt.Sprintf("%s/%s?symbol=%s", LAKEBTC_API_URL, LAKEBTC_TRADES, common.StringToLower(currency)) resp := []LakeBTCTradeHistory{} - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err } @@ -308,7 +310,7 @@ func (l *LakeBTC) GetExchangeAccountInfo() (ExchangeAccountInfo, error) { for z, w := range accountInfo.Locked { if z == x { var exchangeCurrency ExchangeAccountCurrencyInfo - exchangeCurrency.CurrencyName = StringToUpper(x) + exchangeCurrency.CurrencyName = common.StringToUpper(x) exchangeCurrency.TotalValue, _ = strconv.ParseFloat(y, 64) exchangeCurrency.Hold, _ = strconv.ParseFloat(w, 64) response.Currencies = append(response.Currencies, exchangeCurrency) @@ -382,7 +384,7 @@ func (l *LakeBTC) GetOrders(orders []int64) ([]LakeBTCOrders, error) { } resp := []LakeBTCOrders{} - err := l.SendAuthenticatedHTTPRequest(LAKEBTC_GET_ORDERS, JoinStrings(ordersStr, ","), &resp) + err := l.SendAuthenticatedHTTPRequest(LAKEBTC_GET_ORDERS, common.JoinStrings(ordersStr, ","), &resp) if err != nil { return nil, err @@ -477,7 +479,7 @@ func (l *LakeBTC) CreateWithdraw(amount float64, accountID int64) (LakeBTCWithdr func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string, result interface{}) (err error) { nonce := strconv.FormatInt(time.Now().UnixNano(), 10) req := fmt.Sprintf("tonce=%s&accesskey=%s&requestmethod=post&id=1&method=%s¶ms=%s", nonce, l.APIKey, method, params) - hmac := GetHMAC(HASH_SHA1, []byte(req), []byte(l.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA1, []byte(req), []byte(l.APISecret)) if l.Verbose { log.Printf("Sending POST request to %s calling method %s with params %s\n", LAKEBTC_API_URL, method, req) @@ -486,19 +488,19 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string, result int postData := make(map[string]interface{}) postData["method"] = method postData["id"] = 1 - postData["params"] = SplitStrings(params, ",") + postData["params"] = common.SplitStrings(params, ",") - data, err := JSONEncode(postData) + data, err := common.JSONEncode(postData) if err != nil { return err } headers := make(map[string]string) headers["Json-Rpc-Tonce"] = nonce - headers["Authorization"] = "Basic " + Base64Encode([]byte(l.APIKey+":"+HexEncodeToString(hmac))) + headers["Authorization"] = "Basic " + common.Base64Encode([]byte(l.APIKey+":"+common.HexEncodeToString(hmac))) headers["Content-Type"] = "application/json-rpc" - resp, err := SendHTTPRequest("POST", LAKEBTC_API_URL, headers, strings.NewReader(string(data))) + resp, err := common.SendHTTPRequest("POST", LAKEBTC_API_URL, headers, strings.NewReader(string(data))) if err != nil { return err } @@ -512,7 +514,7 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string, result int } errResponse := ErrorResponse{} - err = JSONDecode([]byte(resp), &errResponse) + err = common.JSONDecode([]byte(resp), &errResponse) if err != nil { return errors.New("Unable to check response for error.") } @@ -521,7 +523,7 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string, result int return errors.New(errResponse.Error) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/liquihttp.go b/liquihttp.go index 8bd4c1dd..5bd16c3e 100644 --- a/liquihttp.go +++ b/liquihttp.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -107,9 +109,9 @@ func (l *Liqui) Setup(exch Exchanges) { l.RESTPollingDelay = exch.RESTPollingDelay l.Verbose = exch.Verbose l.Websocket = exch.Websocket - l.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - l.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - l.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + l.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + l.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + l.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -138,14 +140,14 @@ func (l *Liqui) Run() { log.Printf("%s Unable to fetch info.\n", l.GetName()) } else { exchangeProducts := l.GetAvailablePairs(true) - diff := StringSliceDifference(l.AvailablePairs, exchangeProducts) + diff := common.StringSliceDifference(l.AvailablePairs, exchangeProducts) if len(diff) > 0 { exch, err := GetExchangeConfig(l.Name) if err != nil { log.Println(err) } else { log.Printf("%s Updating available pairs. Difference: %s.\n", l.Name, diff) - exch.AvailablePairs = JoinStrings(exchangeProducts, ",") + exch.AvailablePairs = common.JoinStrings(exchangeProducts, ",") UpdateExchangeConfig(exch) } } @@ -153,11 +155,11 @@ func (l *Liqui) Run() { pairs := []string{} for _, x := range l.EnabledPairs { - currencies := SplitStrings(x, "_") - x = StringToLower(currencies[0]) + "_" + StringToLower(currencies[1]) + currencies := common.SplitStrings(x, "_") + x = common.StringToLower(currencies[0]) + "_" + common.StringToLower(currencies[1]) pairs = append(pairs, x) } - pairsString := JoinStrings(pairs, "-") + pairsString := common.JoinStrings(pairs, "-") for l.Enabled { go func() { @@ -167,11 +169,11 @@ func (l *Liqui) Run() { return } for x, y := range ticker { - currencies := SplitStrings(x, "_") - x = StringToUpper(x) + currencies := common.SplitStrings(x, "_") + x = common.StringToUpper(x) log.Printf("Liqui %s: Last %f High %f Low %f Volume %f\n", x, y.Last, y.High, y.Low, y.Vol_cur) l.Ticker[x] = y - AddExchangeInfo(l.GetName(), StringToUpper(currencies[0]), StringToUpper(currencies[1]), y.Last, y.Vol_cur) + AddExchangeInfo(l.GetName(), common.StringToUpper(currencies[0]), common.StringToUpper(currencies[1]), y.Last, y.Vol_cur) } }() time.Sleep(time.Second * l.RESTPollingDelay) @@ -193,7 +195,7 @@ type LiquiInfo struct { } func (l *Liqui) GetFee(currency string) (float64, error) { - val, ok := l.Info.Pairs[StringToLower(currency)] + val, ok := l.Info.Pairs[common.StringToLower(currency)] if !ok { return 0, errors.New("Currency does not exist") } @@ -207,7 +209,7 @@ func (l *Liqui) GetAvailablePairs(nonHidden bool) []string { if nonHidden && y.Hidden == 1 { continue } - pairs = append(pairs, StringToUpper(x)) + pairs = append(pairs, common.StringToUpper(x)) } return pairs } @@ -215,7 +217,7 @@ func (l *Liqui) GetAvailablePairs(nonHidden bool) []string { func (l *Liqui) GetInfo() (LiquiInfo, error) { req := fmt.Sprintf("%s/%s/%s/", LIQUI_API_PUBLIC_URL, LIQUI_API_PUBLIC_VERSION, LIQUI_INFO) resp := LiquiInfo{} - err := SendHTTPGetRequest(req, true, &resp) + err := common.SendHTTPGetRequest(req, true, &resp) if err != nil { return resp, err @@ -231,7 +233,7 @@ func (l *Liqui) GetTicker(symbol string) (map[string]LiquiTicker, error) { response := Response{} req := fmt.Sprintf("%s/%s/%s/%s", LIQUI_API_PUBLIC_URL, LIQUI_API_PUBLIC_VERSION, LIQUI_TICKER, symbol) - err := SendHTTPGetRequest(req, true, &response.Data) + err := common.SendHTTPGetRequest(req, true, &response.Data) if err != nil { return nil, err @@ -247,7 +249,7 @@ func (l *Liqui) GetTickerPrice(currency string) (TickerPrice, error) { } tickerPrice.Ask = ticker.Buy tickerPrice.Bid = ticker.Sell - currencies := SplitStrings(currency, "_") + currencies := common.SplitStrings(currency, "_") tickerPrice.FirstCurrency = currencies[0] tickerPrice.SecondCurrency = currencies[1] tickerPrice.CurrencyPair = tickerPrice.FirstCurrency + "_" + tickerPrice.SecondCurrency @@ -267,7 +269,7 @@ func (l *Liqui) GetDepth(symbol string) (LiquiOrderbook, error) { response := Response{} req := fmt.Sprintf("%s/%s/%s/%s", LIQUI_API_PUBLIC_URL, LIQUI_API_PUBLIC_VERSION, LIQUI_DEPTH, symbol) - err := SendHTTPGetRequest(req, true, &response.Data) + err := common.SendHTTPGetRequest(req, true, &response.Data) if err != nil { return LiquiOrderbook{}, err } @@ -284,7 +286,7 @@ func (l *Liqui) GetTrades(symbol string) ([]LiquiTrades, error) { response := Response{} req := fmt.Sprintf("%s/%s/%s/%s", LIQUI_API_PUBLIC_URL, LIQUI_API_PUBLIC_VERSION, LIQUI_TRADES, symbol) - err := SendHTTPGetRequest(req, true, &response.Data) + err := common.SendHTTPGetRequest(req, true, &response.Data) if err != nil { return []LiquiTrades{}, err } @@ -327,7 +329,7 @@ func (e *Liqui) GetExchangeAccountInfo() (ExchangeAccountInfo, error) { for x, y := range accountBalance.Funds { var exchangeCurrency ExchangeAccountCurrencyInfo - exchangeCurrency.CurrencyName = StringToUpper(x) + exchangeCurrency.CurrencyName = common.StringToUpper(x) exchangeCurrency.TotalValue = y exchangeCurrency.Hold = 0 response.Currencies = append(response.Currencies, exchangeCurrency) @@ -481,7 +483,7 @@ func (l *Liqui) SendAuthenticatedHTTPRequest(method string, values url.Values, r values.Set("method", method) encoded := values.Encode() - hmac := GetHMAC(HASH_SHA512, []byte(encoded), []byte(l.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA512, []byte(encoded), []byte(l.APISecret)) if l.Verbose { log.Printf("Sending POST request to %s calling method %s with params %s\n", LIQUI_API_PRIVATE_URL, method, encoded) @@ -489,17 +491,17 @@ func (l *Liqui) SendAuthenticatedHTTPRequest(method string, values url.Values, r headers := make(map[string]string) headers["Key"] = l.APIKey - headers["Sign"] = HexEncodeToString(hmac) + headers["Sign"] = common.HexEncodeToString(hmac) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", LIQUI_API_PRIVATE_URL, headers, strings.NewReader(encoded)) + resp, err := common.SendHTTPRequest("POST", LIQUI_API_PRIVATE_URL, headers, strings.NewReader(encoded)) if err != nil { return err } response := LiquiResponse{} - err = JSONDecode([]byte(resp), &response) + err = common.JSONDecode([]byte(resp), &response) if err != nil { return err @@ -509,13 +511,13 @@ func (l *Liqui) SendAuthenticatedHTTPRequest(method string, values url.Values, r return errors.New(response.Error) } - jsonEncoded, err := JSONEncode(response.Return) + jsonEncoded, err := common.JSONEncode(response.Return) if err != nil { return err } - err = JSONDecode(jsonEncoded, &result) + err = common.JSONDecode(jsonEncoded, &result) if err != nil { return err diff --git a/localbitcoinshttp.go b/localbitcoinshttp.go index 8dd16c4d..f6eac19c 100644 --- a/localbitcoinshttp.go +++ b/localbitcoinshttp.go @@ -8,6 +8,8 @@ import ( "net/url" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -68,9 +70,9 @@ func (l *LocalBitcoins) Setup(exch Exchanges) { l.RESTPollingDelay = exch.RESTPollingDelay l.Verbose = exch.Verbose l.Websocket = exch.Websocket - l.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - l.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - l.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + l.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + l.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + l.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -130,7 +132,7 @@ type LocalBitcoinsTicker struct { func (l *LocalBitcoins) GetTicker() (map[string]LocalBitcoinsTicker, error) { result := make(map[string]LocalBitcoinsTicker) - err := SendHTTPGetRequest(LOCALBITCOINS_API_URL+LOCALBITCOINS_API_TICKER, true, &result) + err := common.SendHTTPGetRequest(LOCALBITCOINS_API_URL+LOCALBITCOINS_API_TICKER, true, &result) if err != nil { return result, err @@ -170,9 +172,9 @@ type LocalBitcoinsTrade struct { } func (l *LocalBitcoins) GetTrades(currency string, values url.Values) ([]LocalBitcoinsTrade, error) { - path := EncodeURLValues(fmt.Sprintf("%s/%s/trades.json", LOCALBITCOINS_API_URL+LOCALBITCOINS_API_BITCOINCHARTS, currency), values) + path := common.EncodeURLValues(fmt.Sprintf("%s/%s/trades.json", LOCALBITCOINS_API_URL+LOCALBITCOINS_API_BITCOINCHARTS, currency), values) result := []LocalBitcoinsTrade{} - err := SendHTTPGetRequest(path, true, &result) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return result, err @@ -199,7 +201,7 @@ func (l *LocalBitcoins) GetOrderbook(currency string) (LocalBitcoinsOrderbook, e path := fmt.Sprintf("%s/%s/orderbook.json", LOCALBITCOINS_API_URL+LOCALBITCOINS_API_BITCOINCHARTS, currency) resp := response{} - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return LocalBitcoinsOrderbook{}, err @@ -270,7 +272,7 @@ func (l *LocalBitcoins) GetAccountInfo(username string, self bool) (LocalBitcoin } } else { path := fmt.Sprintf("%s/api/account_info/%s/", LOCALBITCOINS_API_URL, username) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return resp.Data, err @@ -432,20 +434,20 @@ func (l *LocalBitcoins) SendAuthenticatedHTTPRequest(method, path string, values } message := string(nonce) + l.APIKey + path + payload - hmac := GetHMAC(HASH_SHA256, []byte(message), []byte(l.APISecret)) + hmac := common.GetHMAC(common.HASH_SHA256, []byte(message), []byte(l.APISecret)) headers := make(map[string]string) headers["Apiauth-Key"] = l.APIKey headers["Apiauth-Nonce"] = string(nonce) - headers["Apiauth-Signature"] = StringToUpper(HexEncodeToString(hmac)) + headers["Apiauth-Signature"] = common.StringToUpper(common.HexEncodeToString(hmac)) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest(method, LOCALBITCOINS_API_URL+path, headers, bytes.NewBuffer([]byte(payload))) + resp, err := common.SendHTTPRequest(method, LOCALBITCOINS_API_URL+path, headers, bytes.NewBuffer([]byte(payload))) if l.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/main.go b/main.go index 14464e34..97071ca9 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,8 @@ import ( "runtime" "strconv" "syscall" + + "github.com/thrasher-/gocryptotrader/common" ) type Exchange struct { @@ -48,10 +50,10 @@ func setupBotExchanges() { if bot.exchanges[i].GetName() == exch.Name { bot.exchanges[i].Setup(exch) if bot.exchanges[i].IsEnabled() { - log.Printf("%s: Exchange support: %s (Authenticated API support: %s - Verbose mode: %s).\n", exch.Name, IsEnabled(exch.Enabled), IsEnabled(exch.AuthenticatedAPISupport), IsEnabled(exch.Verbose)) + log.Printf("%s: Exchange support: %s (Authenticated API support: %s - Verbose mode: %s).\n", exch.Name, common.IsEnabled(exch.Enabled), common.IsEnabled(exch.AuthenticatedAPISupport), common.IsEnabled(exch.Verbose)) bot.exchanges[i].Start() } else { - log.Printf("%s: Exchange support: %s\n", exch.Name, IsEnabled(exch.Enabled)) + log.Printf("%s: Exchange support: %s\n", exch.Name, common.IsEnabled(exch.Enabled)) } } } @@ -130,7 +132,7 @@ func main() { //bot.config.Webserver.Enabled = false } else { listenAddr := bot.config.Webserver.ListenAddress - log.Printf("HTTP Webserver support enabled. Listen URL: http://%s:%d/\n", ExtractHost(listenAddr), ExtractPort(listenAddr)) + log.Printf("HTTP Webserver support enabled. Listen URL: http://%s:%d/\n", common.ExtractHost(listenAddr), common.ExtractPort(listenAddr)) router := NewRouter(bot.exchanges) log.Fatal(http.ListenAndServe(listenAddr, router)) } diff --git a/okcoinhttp.go b/okcoinhttp.go index 4f9d5758..e2dfe2c2 100644 --- a/okcoinhttp.go +++ b/okcoinhttp.go @@ -9,6 +9,7 @@ import ( "time" "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -231,9 +232,9 @@ func (o *OKCoin) Setup(exch Exchanges) { o.RESTPollingDelay = exch.RESTPollingDelay o.Verbose = exch.Verbose o.Websocket = exch.Websocket - o.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - o.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - o.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + o.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + o.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + o.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -268,7 +269,7 @@ func (o *OKCoin) GetFee(maker bool) float64 { func (o *OKCoin) Run() { if o.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", o.GetName(), IsEnabled(o.Websocket), o.WebsocketURL) + log.Printf("%s Websocket: %s. (url: %s).\n", o.GetName(), common.IsEnabled(o.Websocket), o.WebsocketURL) log.Printf("%s polling delay: %ds.\n", o.GetName(), o.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", o.GetName(), len(o.EnabledPairs), o.EnabledPairs) } @@ -279,7 +280,7 @@ func (o *OKCoin) Run() { for o.Enabled { for _, x := range o.EnabledPairs { - currency := StringToLower(x[0:3] + "_" + x[3:]) + currency := common.StringToLower(x[0:3] + "_" + x[3:]) if o.APIUrl == OKCOIN_API_URL { for _, y := range o.FuturesValues { futuresValue := y @@ -290,7 +291,7 @@ func (o *OKCoin) Run() { return } log.Printf("OKCoin Intl Futures %s (%s): Last %f High %f Low %f Volume %f\n", currency, futuresValue, ticker.Last, ticker.High, ticker.Low, ticker.Vol) - AddExchangeInfo(o.GetName(), StringToUpper(currency[0:3]), StringToUpper(currency[4:]), ticker.Last, ticker.Vol) + AddExchangeInfo(o.GetName(), common.StringToUpper(currency[0:3]), common.StringToUpper(currency[4:]), ticker.Last, ticker.Vol) }() } go func() { @@ -300,7 +301,7 @@ func (o *OKCoin) Run() { return } log.Printf("OKCoin Intl Spot %s: Last %f High %f Low %f Volume %f\n", currency, ticker.Last, ticker.High, ticker.Low, ticker.Volume) - AddExchangeInfo(o.GetName(), StringToUpper(currency[0:3]), StringToUpper(currency[4:]), ticker.Last, ticker.Volume) + AddExchangeInfo(o.GetName(), common.StringToUpper(currency[0:3]), common.StringToUpper(currency[4:]), ticker.Last, ticker.Volume) }() } else { go func() { @@ -313,8 +314,8 @@ func (o *OKCoin) Run() { tickerHighUSD, _ := ConvertCurrency(ticker.High, "CNY", "USD") tickerLowUSD, _ := ConvertCurrency(ticker.Low, "CNY", "USD") log.Printf("OKCoin China %s: Last %f (%f) High %f (%f) Low %f (%f) Volume %f\n", currency, tickerLastUSD, ticker.Last, tickerHighUSD, ticker.High, tickerLowUSD, ticker.Low, ticker.Volume) - AddExchangeInfo(o.GetName(), StringToUpper(currency[0:3]), StringToUpper(currency[4:]), ticker.Last, ticker.Volume) - AddExchangeInfo(o.GetName(), StringToUpper(currency[0:3]), "USD", tickerLastUSD, ticker.Volume) + AddExchangeInfo(o.GetName(), common.StringToUpper(currency[0:3]), common.StringToUpper(currency[4:]), ticker.Last, ticker.Volume) + AddExchangeInfo(o.GetName(), common.StringToUpper(currency[0:3]), "USD", tickerLastUSD, ticker.Volume) }() } } @@ -326,8 +327,8 @@ func (o *OKCoin) GetTicker(symbol string) (OKCoinTicker, error) { resp := OKCoinTickerResponse{} vals := url.Values{} vals.Set("symbol", symbol) - path := EncodeURLValues(o.APIUrl+OKCOIN_TICKER, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_TICKER, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return OKCoinTicker{}, err } @@ -347,8 +348,8 @@ func (o *OKCoin) GetTickerPrice(currency string) (TickerPrice, error) { } tickerPrice.Ask = ticker.Sell tickerPrice.Bid = ticker.Buy - tickerPrice.FirstCurrency = StringToUpper(currency[0:3]) - tickerPrice.SecondCurrency = StringToUpper(currency[4:]) + tickerPrice.FirstCurrency = common.StringToUpper(currency[0:3]) + tickerPrice.SecondCurrency = common.StringToUpper(currency[4:]) tickerPrice.CurrencyPair = tickerPrice.FirstCurrency + "_" + tickerPrice.SecondCurrency tickerPrice.Low = ticker.Low tickerPrice.Last = ticker.Last @@ -369,8 +370,8 @@ func (o *OKCoin) GetOrderBook(symbol string, size int64, merge bool) (OKCoinOrde vals.Set("merge", "1") } - path := EncodeURLValues(o.APIUrl+OKCOIN_DEPTH, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_DEPTH, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return resp, err } @@ -394,8 +395,8 @@ func (o *OKCoin) GetTrades(symbol string, since int64) ([]OKCoinTrades, error) { vals.Set("since", strconv.FormatInt(since, 10)) } - path := EncodeURLValues(o.APIUrl+OKCOIN_TRADES, vals) - err := SendHTTPGetRequest(path, true, &result) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_TRADES, vals) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return nil, err } @@ -416,8 +417,8 @@ func (o *OKCoin) GetKline(symbol, klineType string, size, since int64) ([]interf vals.Set("since", strconv.FormatInt(since, 10)) } - path := EncodeURLValues(o.APIUrl+OKCOIN_KLINE, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_KLINE, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err } @@ -430,8 +431,8 @@ func (o *OKCoin) GetFuturesTicker(symbol, contractType string) (OKCoinFuturesTic vals := url.Values{} vals.Set("symbol", symbol) vals.Set("contract_type", contractType) - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_TICKER, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_TICKER, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return OKCoinFuturesTicker{}, err } @@ -451,8 +452,8 @@ func (o *OKCoin) GetFuturesDepth(symbol, contractType string, size int64, merge vals.Set("merge", "1") } - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_DEPTH, vals) - err := SendHTTPGetRequest(path, true, &result) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_DEPTH, vals) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return result, err } @@ -474,8 +475,8 @@ func (o *OKCoin) GetFuturesTrades(symbol, contractType string) ([]OKCoinFuturesT vals.Set("symbol", symbol) vals.Set("contract_type", contractType) - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_TRADES, vals) - err := SendHTTPGetRequest(path, true, &result) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_TRADES, vals) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return nil, err } @@ -491,8 +492,8 @@ func (o *OKCoin) GetFuturesIndex(symbol string) (float64, error) { vals := url.Values{} vals.Set("symbol", symbol) - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_INDEX, vals) - err := SendHTTPGetRequest(path, true, &result) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_INDEX, vals) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return 0, err } @@ -505,7 +506,7 @@ func (o *OKCoin) GetFuturesExchangeRate() (float64, error) { } result := Response{} - err := SendHTTPGetRequest(o.APIUrl+OKCOIN_EXCHANGE_RATE, true, &result) + err := common.SendHTTPGetRequest(o.APIUrl+OKCOIN_EXCHANGE_RATE, true, &result) if err != nil { return result.Rate, err } @@ -520,8 +521,8 @@ func (o *OKCoin) GetFuturesEstimatedPrice(symbol string) (float64, error) { result := Response{} vals := url.Values{} vals.Set("symbol", symbol) - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_ESTIMATED_PRICE, vals) - err := SendHTTPGetRequest(path, true, &result) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_ESTIMATED_PRICE, vals) + err := common.SendHTTPGetRequest(path, true, &result) if err != nil { return result.Price, err } @@ -542,8 +543,8 @@ func (o *OKCoin) GetFuturesKline(symbol, klineType, contractType string, size, s vals.Set("since", strconv.FormatInt(since, 10)) } - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_KLINE, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_KLINE, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err @@ -557,8 +558,8 @@ func (o *OKCoin) GetFuturesHoldAmount(symbol, contractType string) ([]OKCoinFutu vals.Set("symbol", symbol) vals.Set("contract_type", contractType) - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_HOLD_AMOUNT, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_HOLD_AMOUNT, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err @@ -578,8 +579,8 @@ func (o *OKCoin) GetFuturesExplosive(symbol, contractType string, status, curren vals.Set("current_page", strconv.FormatInt(currentPage, 10)) vals.Set("page_length", strconv.FormatInt(pageLength, 10)) - path := EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_EXPLOSIVE, vals) - err := SendHTTPGetRequest(path, true, &resp) + path := common.EncodeURLValues(o.APIUrl+OKCOIN_FUTURES_EXPLOSIVE, vals) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err @@ -710,7 +711,7 @@ func (o *OKCoin) CancelOrder(orderID []int64, symbol string) (OKCoinCancelOrderR for x := range orderID { orders = append(orders, strconv.FormatInt(orderID[x], 10)) } - orderStr = JoinStrings(orders, ",") + orderStr = common.JoinStrings(orders, ",") } else { orderStr = strconv.FormatInt(orderID[0], 10) } @@ -776,7 +777,7 @@ func (o *OKCoin) GetOrderInfoBatch(orderID []int64, symbol string) ([]OKCoinOrde v := url.Values{} v.Set("symbol", symbol) - v.Set("order_id", JoinStrings(orders, ",")) + v.Set("order_id", common.JoinStrings(orders, ",")) result := Response{} err := o.SendAuthenticatedHTTPRequest(OKCOIN_ORDER_INFO, v, &result) @@ -1221,8 +1222,8 @@ func (o *OKCoin) GetFuturesUserPosition4Fix(symbol, contractType string) { func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values, result interface{}) (err error) { v.Set("api_key", o.PartnerID) - hasher := GetMD5([]byte(v.Encode() + "&secret_key=" + o.SecretKey)) - v.Set("sign", strings.ToUpper(HexEncodeToString(hasher))) + hasher := common.GetMD5([]byte(v.Encode() + "&secret_key=" + o.SecretKey)) + v.Set("sign", strings.ToUpper(common.HexEncodeToString(hasher))) encoded := v.Encode() path := o.APIUrl + method @@ -1234,7 +1235,7 @@ func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values, resul headers := make(map[string]string) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", path, headers, strings.NewReader(encoded)) + resp, err := common.SendHTTPRequest("POST", path, headers, strings.NewReader(encoded)) if err != nil { return err @@ -1244,7 +1245,7 @@ func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values, resul log.Printf("Recieved raw: \n%s\n", resp) } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/okcoinwebsocket.go b/okcoinwebsocket.go index f9320379..675fd047 100644 --- a/okcoinwebsocket.go +++ b/okcoinwebsocket.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "github.com/gorilla/websocket" "log" "net/http" "net/url" @@ -10,6 +9,9 @@ import ( "strconv" "strings" "time" + + "github.com/gorilla/websocket" + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -215,7 +217,7 @@ func (o *OKCoin) PingHandler(message string) error { func (o *OKCoin) AddChannel(channel string) { event := OKCoinWebsocketEvent{"addChannel", channel} - json, err := JSONEncode(event) + json, err := common.JSONEncode(event) if err != nil { log.Println(err) return @@ -234,7 +236,7 @@ func (o *OKCoin) AddChannel(channel string) { func (o *OKCoin) RemoveChannel(channel string) { event := OKCoinWebsocketEvent{"removeChannel", channel} - json, err := JSONEncode(event) + json, err := common.JSONEncode(event) if err != nil { log.Println(err) return @@ -340,13 +342,13 @@ func (o *OKCoin) ConvertToURLValues(values map[string]string) url.Values { func (o *OKCoin) WebsocketSign(values map[string]string) string { values["api_key"] = o.PartnerID urlVals := o.ConvertToURLValues(values) - return strings.ToUpper(HexEncodeToString(GetMD5([]byte(urlVals.Encode() + "&secret_key=" + o.SecretKey)))) + return strings.ToUpper(common.HexEncodeToString(common.GetMD5([]byte(urlVals.Encode() + "&secret_key=" + o.SecretKey)))) } func (o *OKCoin) AddChannelAuthenticated(channel string, values map[string]string) { values["sign"] = o.WebsocketSign(values) event := OKCoinWebsocketEventAuth{"addChannel", channel, values} - json, err := JSONEncode(event) + json, err := common.JSONEncode(event) if err != nil { log.Println(err) return @@ -366,7 +368,7 @@ func (o *OKCoin) AddChannelAuthenticated(channel string, values map[string]strin func (o *OKCoin) RemoveChannelAuthenticated(conn *websocket.Conn, channel string, values map[string]string) { values["sign"] = o.WebsocketSign(values) event := OKCoinWebsocketEventAuthRemove{"removeChannel", channel, values} - json, err := JSONEncode(event) + json, err := common.JSONEncode(event) if err != nil { log.Println(err) return @@ -421,7 +423,7 @@ func (o *OKCoin) WebsocketClient() { } for _, x := range o.EnabledPairs { - currency := StringToLower(x) + currency := common.StringToLower(x) currencyUL := currency[0:3] + "_" + currency[3:] if o.AuthenticatedAPISupport { o.WebsocketSpotOrderInfo(currencyUL, -1) @@ -459,7 +461,7 @@ func (o *OKCoin) WebsocketClient() { switch msgType { case websocket.TextMessage: response := []interface{}{} - err = JSONDecode(resp, &response) + err = common.JSONDecode(resp, &response) if err != nil { log.Println(err) @@ -496,7 +498,7 @@ func (o *OKCoin) WebsocketClient() { } } - dataJSON, err := JSONEncode(data) + dataJSON, err := common.JSONEncode(data) if err != nil { log.Println(err) @@ -504,7 +506,7 @@ func (o *OKCoin) WebsocketClient() { } switch true { - case StringContains(channelStr, "ticker") && !StringContains(channelStr, "future"): + case common.StringContains(channelStr, "ticker") && !common.StringContains(channelStr, "future"): tickerValues := []string{"buy", "high", "last", "low", "sell", "timestamp"} tickerMap := data.(map[string]interface{}) ticker := OKCoinWebsocketTicker{} @@ -551,124 +553,124 @@ func (o *OKCoin) WebsocketClient() { } } } - case StringContains(channelStr, "ticker") && StringContains(channelStr, "future"): + case common.StringContains(channelStr, "ticker") && common.StringContains(channelStr, "future"): ticker := OKCoinWebsocketFuturesTicker{} - err = JSONDecode(dataJSON, &ticker) + err = common.JSONDecode(dataJSON, &ticker) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "depth"): + case common.StringContains(channelStr, "depth"): orderbook := OKCoinWebsocketOrderbook{} - err = JSONDecode(dataJSON, &orderbook) + err = common.JSONDecode(dataJSON, &orderbook) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "trades_v1") || StringContains(channelStr, "trade_v1"): + case common.StringContains(channelStr, "trades_v1") || common.StringContains(channelStr, "trade_v1"): type TradeResponse struct { Data [][]string } trades := TradeResponse{} - err = JSONDecode(dataJSON, &trades.Data) + err = common.JSONDecode(dataJSON, &trades.Data) if err != nil { log.Println(err) continue } // to-do: convert from string array to trade struct - case StringContains(channelStr, "kline"): + case common.StringContains(channelStr, "kline"): klines := []interface{}{} - err := JSONDecode(dataJSON, &klines) + err := common.JSONDecode(dataJSON, &klines) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "spot") && StringContains(channelStr, "realtrades"): + case common.StringContains(channelStr, "spot") && common.StringContains(channelStr, "realtrades"): if string(dataJSON) == "null" { continue } realtrades := OKCoinWebsocketRealtrades{} - err := JSONDecode(dataJSON, &realtrades) + err := common.JSONDecode(dataJSON, &realtrades) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "future") && StringContains(channelStr, "realtrades"): + case common.StringContains(channelStr, "future") && common.StringContains(channelStr, "realtrades"): if string(dataJSON) == "null" { continue } realtrades := OKCoinWebsocketFuturesRealtrades{} - err := JSONDecode(dataJSON, &realtrades) + err := common.JSONDecode(dataJSON, &realtrades) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "spot") && StringContains(channelStr, "trade") || StringContains(channelStr, "futures") && StringContains(channelStr, "trade"): + case common.StringContains(channelStr, "spot") && common.StringContains(channelStr, "trade") || common.StringContains(channelStr, "futures") && common.StringContains(channelStr, "trade"): tradeOrder := OKCoinWebsocketTradeOrderResponse{} - err := JSONDecode(dataJSON, &tradeOrder) + err := common.JSONDecode(dataJSON, &tradeOrder) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "cancel_order"): + case common.StringContains(channelStr, "cancel_order"): cancelOrder := OKCoinWebsocketTradeOrderResponse{} - err := JSONDecode(dataJSON, &cancelOrder) + err := common.JSONDecode(dataJSON, &cancelOrder) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "spot") && StringContains(channelStr, "userinfo"): + case common.StringContains(channelStr, "spot") && common.StringContains(channelStr, "userinfo"): userinfo := OKCoinWebsocketUserinfo{} - err = JSONDecode(dataJSON, &userinfo) + err = common.JSONDecode(dataJSON, &userinfo) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "futureusd_userinfo"): + case common.StringContains(channelStr, "futureusd_userinfo"): userinfo := OKCoinWebsocketFuturesUserInfo{} - err = JSONDecode(dataJSON, &userinfo) + err = common.JSONDecode(dataJSON, &userinfo) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "spot") && StringContains(channelStr, "order_info"): + case common.StringContains(channelStr, "spot") && common.StringContains(channelStr, "order_info"): type OrderInfoResponse struct { Result bool `json:"result"` Orders []OKCoinWebsocketOrder `json:"orders"` } var orders OrderInfoResponse - err := JSONDecode(dataJSON, &orders) + err := common.JSONDecode(dataJSON, &orders) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "futureusd_order_info"): + case common.StringContains(channelStr, "futureusd_order_info"): type OrderInfoResponse struct { Result bool `json:"result"` Orders []OKCoinWebsocketFuturesOrder `json:"orders"` } var orders OrderInfoResponse - err := JSONDecode(dataJSON, &orders) + err := common.JSONDecode(dataJSON, &orders) if err != nil { log.Println(err) continue } - case StringContains(channelStr, "future_index"): + case common.StringContains(channelStr, "future_index"): index := OKCoinWebsocketFutureIndex{} - err = JSONDecode(dataJSON, &index) + err = common.JSONDecode(dataJSON, &index) if err != nil { log.Println(err) diff --git a/poloniexhttp.go b/poloniexhttp.go index 9627a19a..47c88afb 100644 --- a/poloniexhttp.go +++ b/poloniexhttp.go @@ -8,6 +8,8 @@ import ( "net/url" "strconv" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -99,9 +101,9 @@ func (p *Poloniex) Setup(exch Exchanges) { p.RESTPollingDelay = exch.RESTPollingDelay p.Verbose = exch.Verbose p.Websocket = exch.Websocket - p.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") - p.AvailablePairs = SplitStrings(exch.AvailablePairs, ",") - p.EnabledPairs = SplitStrings(exch.EnabledPairs, ",") + p.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",") + p.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",") + p.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",") } } @@ -124,7 +126,7 @@ func (p *Poloniex) GetFee() float64 { func (p *Poloniex) Run() { if p.Verbose { - log.Printf("%s Websocket: %s (url: %s).\n", p.GetName(), IsEnabled(p.Websocket), POLONIEX_WEBSOCKET_ADDRESS) + log.Printf("%s Websocket: %s (url: %s).\n", p.GetName(), common.IsEnabled(p.Websocket), POLONIEX_WEBSOCKET_ADDRESS) log.Printf("%s polling delay: %ds.\n", p.GetName(), p.RESTPollingDelay) log.Printf("%s %d currencies enabled: %s.\n", p.GetName(), len(p.EnabledPairs), p.EnabledPairs) } @@ -143,7 +145,7 @@ func (p *Poloniex) Run() { return } log.Printf("Poloniex %s Last %f High %f Low %f Volume %f\n", currency, ticker.Last, ticker.High, ticker.Low, ticker.Volume) - currencyPair := SplitStrings(currency, "_") + currencyPair := common.SplitStrings(currency, "_") AddExchangeInfo(p.GetName(), currencyPair[0], currencyPair[1], ticker.Last, ticker.Volume) }() } @@ -158,7 +160,7 @@ func (p *Poloniex) GetTicker() (map[string]PoloniexTicker, error) { resp := response{} path := fmt.Sprintf("%s/public?command=returnTicker", POLONIEX_API_URL) - err := SendHTTPGetRequest(path, true, &resp.Data) + err := common.SendHTTPGetRequest(path, true, &resp.Data) if err != nil { return resp.Data, err @@ -178,7 +180,7 @@ func (p *Poloniex) GetTickerPrice(currency string) (TickerPrice, error) { return tickerPrice, err } - currencyPair := SplitStrings(currency, "_") + currencyPair := common.SplitStrings(currency, "_") tickerPrice.FirstCurrency = currencyPair[0] tickerPrice.SecondCurrency = currencyPair[1] tickerPrice.CurrencyPair = tickerPrice.FirstCurrency + "_" + tickerPrice.SecondCurrency @@ -195,7 +197,7 @@ func (p *Poloniex) GetTickerPrice(currency string) (TickerPrice, error) { func (p *Poloniex) GetVolume() (interface{}, error) { var resp interface{} path := fmt.Sprintf("%s/public?command=return24hVolume", POLONIEX_API_URL) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return resp, err @@ -224,7 +226,7 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (map[string]Polo resp := Response{} path := fmt.Sprintf("%s/public?command=returnOrderBook&%s", POLONIEX_API_URL, vals.Encode()) - err := SendHTTPGetRequest(path, true, &resp.Data) + err := common.SendHTTPGetRequest(path, true, &resp.Data) if err != nil { return resp.Data, err @@ -256,7 +258,7 @@ func (p *Poloniex) GetTradeHistory(currencyPair, start, end string) ([]PoloniexT resp := []PoloniexTradeHistory{} path := fmt.Sprintf("%s/public?command=returnTradeHistory&%s", POLONIEX_API_URL, vals.Encode()) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err @@ -293,7 +295,7 @@ func (p *Poloniex) GetChartData(currencyPair, start, end, period string) ([]Polo resp := []PoloniexChartData{} path := fmt.Sprintf("%s/public?command=returnChartData&%s", POLONIEX_API_URL, vals.Encode()) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return nil, err @@ -318,7 +320,7 @@ func (p *Poloniex) GetCurrencies() (map[string]PoloniexCurrencies, error) { } resp := Response{} path := fmt.Sprintf("%s/public?command=returnCurrencies", POLONIEX_API_URL) - err := SendHTTPGetRequest(path, true, &resp.Data) + err := common.SendHTTPGetRequest(path, true, &resp.Data) if err != nil { return resp.Data, err @@ -341,7 +343,7 @@ type PoloniexLoanOrders struct { func (p *Poloniex) GetLoanOrders(currency string) (PoloniexLoanOrders, error) { resp := PoloniexLoanOrders{} path := fmt.Sprintf("%s/public?command=returnLoanOrders¤cy=%s", POLONIEX_API_URL, currency) - err := SendHTTPGetRequest(path, true, &resp) + err := common.SendHTTPGetRequest(path, true, &resp) if err != nil { return resp, err @@ -1020,17 +1022,17 @@ func (p *Poloniex) SendAuthenticatedHTTPRequest(method, endpoint string, values values.Set("nonce", nonceStr) values.Set("command", endpoint) - hmac := GetHMAC(HASH_SHA512, []byte(values.Encode()), []byte(p.SecretKey)) - headers["Sign"] = HexEncodeToString(hmac) + hmac := common.GetHMAC(common.HASH_SHA512, []byte(values.Encode()), []byte(p.SecretKey)) + headers["Sign"] = common.HexEncodeToString(hmac) path := fmt.Sprintf("%s/%s", POLONIEX_API_URL, POLONIEX_API_TRADING_ENDPOINT) - resp, err := SendHTTPRequest(method, path, headers, bytes.NewBufferString(values.Encode())) + resp, err := common.SendHTTPRequest(method, path, headers, bytes.NewBufferString(values.Encode())) if err != nil { return err } - err = JSONDecode([]byte(resp), &result) + err = common.JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") diff --git a/portfolio.go b/portfolio.go index 2dbb566e..6226a450 100644 --- a/portfolio.go +++ b/portfolio.go @@ -5,6 +5,8 @@ import ( "fmt" "log" "time" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -60,10 +62,10 @@ type EtherchainBalanceResponse struct { } func GetEthereumBalance(address []string) (EtherchainBalanceResponse, error) { - addresses := JoinStrings(address, ",") + addresses := common.JoinStrings(address, ",") url := fmt.Sprintf("%s/%s/%s", ETHERCHAIN_API_URL, ETHERCHAIN_ACCOUNT_MULTIPLE, addresses) result := EtherchainBalanceResponse{} - err := SendHTTPGetRequest(url, true, &result) + err := common.SendHTTPGetRequest(url, true, &result) if err != nil { return result, err } @@ -74,9 +76,9 @@ func GetEthereumBalance(address []string) (EtherchainBalanceResponse, error) { } func GetBlockrBalanceSingle(address string, coinType string) (BlockrAddressBalanceSingle, error) { - url := fmt.Sprintf("https://%s.%s/v%s/%s/%s", StringToLower(coinType), BLOCKR_API_URL, BLOCKR_API_VERSION, BLOCKR_ADDRESS_BALANCE, address) + url := fmt.Sprintf("https://%s.%s/v%s/%s/%s", common.StringToLower(coinType), BLOCKR_API_URL, BLOCKR_API_VERSION, BLOCKR_ADDRESS_BALANCE, address) result := BlockrAddressBalanceSingle{} - err := SendHTTPGetRequest(url, true, &result) + err := common.SendHTTPGetRequest(url, true, &result) if err != nil { return result, err } @@ -87,10 +89,10 @@ func GetBlockrBalanceSingle(address string, coinType string) (BlockrAddressBalan } func GetBlockrAddressMulti(addresses []string, coinType string) (BlockrAddressBalanceMulti, error) { - addressesStr := JoinStrings(addresses, ",") - url := fmt.Sprintf("https://%s.%s/v%s/%s/%s", StringToLower(coinType), BLOCKR_API_URL, BLOCKR_API_VERSION, BLOCKR_ADDRESS_BALANCE, addressesStr) + addressesStr := common.JoinStrings(addresses, ",") + url := fmt.Sprintf("https://%s.%s/v%s/%s/%s", common.StringToLower(coinType), BLOCKR_API_URL, BLOCKR_API_VERSION, BLOCKR_ADDRESS_BALANCE, addressesStr) result := BlockrAddressBalanceMulti{} - err := SendHTTPGetRequest(url, true, &result) + err := common.SendHTTPGetRequest(url, true, &result) if err != nil { return result, err } @@ -134,7 +136,7 @@ func UpdatePortfolio(addresses []string, coinType string) bool { } for _, x := range result.Data { if !AddressExists(x.Address) { - bot.config.Portfolio.Addresses = append(bot.config.Portfolio.Addresses, PortfolioAddress{Address: x.Address, CoinType: coinType, Balance: x.Balance / WEI_PER_ETHER}) + bot.config.Portfolio.Addresses = append(bot.config.Portfolio.Addresses, PortfolioAddress{Address: x.Address, CoinType: coinType, Balance: x.Balance / common.WEI_PER_ETHER}) } else { UpdateAddressBalance(x.Address, x.Balance) } diff --git a/smsglobal.go b/smsglobal.go index e9367018..48280c9e 100644 --- a/smsglobal.go +++ b/smsglobal.go @@ -5,6 +5,8 @@ import ( "log" "net/url" "strings" + + "github.com/thrasher-/gocryptotrader/common" ) const ( @@ -55,13 +57,13 @@ func SMSNotify(to, message string) error { headers := make(map[string]string) headers["Content-Type"] = "application/x-www-form-urlencoded" - resp, err := SendHTTPRequest("POST", SMSGLOBAL_API_URL, headers, strings.NewReader(values.Encode())) + resp, err := common.SendHTTPRequest("POST", SMSGLOBAL_API_URL, headers, strings.NewReader(values.Encode())) if err != nil { return err } - if !StringContains(resp, "OK: 0; Sent queued message") { + if !common.StringContains(resp, "OK: 0; Sent queued message") { return errors.New(ErrSMSNotSent) } return nil