Skip to content

Commit

Permalink
In the common package added JSONDecode error check. Added verbosity i…
Browse files Browse the repository at this point in the history
…n SendHTTPGetRequest. Updated Nonce package function. Fixed issues in ItBit package and expanded test coverage.
  • Loading branch information
shazbert committed Oct 3, 2017
1 parent 939ce3a commit e8c7bf9
Show file tree
Hide file tree
Showing 24 changed files with 599 additions and 239 deletions.
22 changes: 18 additions & 4 deletions common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -294,33 +295,43 @@ func SendHTTPRequest(method, path string, headers map[string]string, body io.Rea
// SendHTTPGetRequest sends a simple get request using a url string & JSON
// decodes the response into a struct pointer you have supplied. Returns an error
// on failure.
func SendHTTPGetRequest(url string, jsonDecode bool, result interface{}) error {
func SendHTTPGetRequest(url string, jsonDecode, isVerbose bool, result interface{}) error {
if isVerbose {
log.Println("Raw URL: ", url)
}

res, err := http.Get(url)
if err != nil {
return err
}

if res.StatusCode != 200 {
<<<<<<< dae90a2eaa109648bdb85f8298d805e00ad4e974
log.Printf("HTTP status code: %d\n", res.StatusCode)
log.Printf("URL: %s\n", url)
return errors.New("status code was not 200")
=======
return fmt.Errorf("common.SendHTTPGetRequest() error: HTTP status code %d", res.StatusCode)
>>>>>>> In the common package added JSONDecode error check. Added verbosity in SendHTTPGetRequest. Updated Nonce package function. Fixed issues in ItBit package and expanded test coverage.
}

contents, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}

if isVerbose {
log.Println("Raw Resp: ", string(contents[:]))
}

defer res.Body.Close()

if jsonDecode {
err := JSONDecode(contents, &result)
err := JSONDecode(contents, result)
if err != nil {
log.Println(string(contents[:]))
return err
}
} else {
result = &contents
}

return nil
Expand All @@ -333,6 +344,9 @@ func JSONEncode(v interface{}) ([]byte, error) {

// JSONDecode decodes JSON data into a structure
func JSONDecode(data []byte, to interface{}) error {
if !StringContains(reflect.ValueOf(to).Type().String(), "*") {
return errors.New("json decode error - memory address not supplied")
}
return json.Unmarshal(data, to)
}

Expand Down
6 changes: 3 additions & 3 deletions common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,15 +488,15 @@ func TestSendHTTPGetRequest(t *testing.T) {
url := `https://etherchain.org/api/account/multiple/0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe`
result := test{}

err := SendHTTPGetRequest(url, true, &result)
err := SendHTTPGetRequest(url, true, false, &result)
if err != nil {
t.Errorf("Test failed - common SendHTTPGetRequest error: %s", err)
}
err = SendHTTPGetRequest("DINGDONG", true, &result)
err = SendHTTPGetRequest("DINGDONG", true, false, &result)
if err == nil {
t.Error("Test failed - common SendHTTPGetRequest error")
}
err = SendHTTPGetRequest(url, false, &result)
err = SendHTTPGetRequest(url, false, false, &result)
if err != nil {
t.Error("Test failed - common SendHTTPGetRequest error")
}
Expand Down
2 changes: 1 addition & 1 deletion currency/currency.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func FetchFixerCurrencyData() error {

CurrencyStoreFixer = make(map[string]float64)

err := common.SendHTTPGetRequest(url, true, &result)
err := common.SendHTTPGetRequest(url, true, false, &result)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion exchanges/anx/anx.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (a *ANX) GetFee(maker bool) float64 {

func (a *ANX) GetTicker(currency string) (ANXTicker, error) {
var ticker ANXTicker
err := common.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, a.Verbose, &ticker)
if err != nil {
return ANXTicker{}, err
}
Expand Down
18 changes: 9 additions & 9 deletions exchanges/bitfinex/bitfinex.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,15 @@ func (b *Bitfinex) GetTicker(symbol string, values url.Values) (Ticker, error) {
response := Ticker{}
path := common.EncodeURLValues(bitfinexAPIURL+bitfinexTicker+symbol, values)

return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetStats returns various statistics about the requested pair
func (b *Bitfinex) GetStats(symbol string) ([]Stat, error) {
response := []Stat{}
path := fmt.Sprint(bitfinexAPIURL + bitfinexStats + symbol)

return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetFundingBook the entire margin funding book for both bids and asks sides
Expand All @@ -137,7 +137,7 @@ func (b *Bitfinex) GetFundingBook(symbol string) (FundingBook, error) {
response := FundingBook{}
path := fmt.Sprint(bitfinexAPIURL + bitfinexLendbook + symbol)

return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetOrderbook retieves the entire orderbook bid and ask price on a currency
Expand All @@ -149,7 +149,7 @@ func (b *Bitfinex) GetOrderbook(currencyPair string, values url.Values) (Orderbo
bitfinexAPIURL+bitfinexOrderbook+currencyPair,
values,
)
return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetTrades returns a list of the most recent trades for the given curencyPair
Expand All @@ -160,7 +160,7 @@ func (b *Bitfinex) GetTrades(currencyPair string, values url.Values) ([]TradeStr
bitfinexAPIURL+bitfinexTrades+currencyPair,
values,
)
return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetLendbook returns a list of the most recent funding data for the given
Expand All @@ -174,7 +174,7 @@ func (b *Bitfinex) GetLendbook(symbol string, values url.Values) (Lendbook, erro
}
path := common.EncodeURLValues(bitfinexAPIURL+bitfinexLendbook+symbol, values)

return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetLends returns a list of the most recent funding data for the given
Expand All @@ -185,23 +185,23 @@ func (b *Bitfinex) GetLends(symbol string, values url.Values) ([]Lends, error) {
response := []Lends{}
path := common.EncodeURLValues(bitfinexAPIURL+bitfinexLends+symbol, values)

return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetSymbols returns the avaliable currency pairs on the exchange
func (b *Bitfinex) GetSymbols() ([]string, error) {
products := []string{}
path := fmt.Sprint(bitfinexAPIURL + bitfinexSymbols)

return products, common.SendHTTPGetRequest(path, true, &products)
return products, common.SendHTTPGetRequest(path, true, b.Verbose, &products)
}

// GetSymbolsDetails a list of valid symbol IDs and the pair details
func (b *Bitfinex) GetSymbolsDetails() ([]SymbolDetails, error) {
response := []SymbolDetails{}
path := fmt.Sprint(bitfinexAPIURL + bitfinexSymbolsDetails)

return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetAccountInfo returns information about your account incl. trading fees
Expand Down
8 changes: 4 additions & 4 deletions exchanges/bitstamp/bitstamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (b *Bitstamp) GetTicker(currency string, hourly bool) (Ticker, error) {
tickerEndpoint,
common.StringToLower(currency),
)
return response, common.SendHTTPGetRequest(path, true, &response)
return response, common.SendHTTPGetRequest(path, true, b.Verbose, &response)
}

// GetOrderbook Returns a JSON dictionary with "bids" and "asks". Each is a list
Expand All @@ -149,7 +149,7 @@ func (b *Bitstamp) GetOrderbook(currency string) (Orderbook, error) {
common.StringToLower(currency),
)

err := common.SendHTTPGetRequest(path, true, &resp)
err := common.SendHTTPGetRequest(path, true, b.Verbose, &resp)
if err != nil {
return Orderbook{}, err
}
Expand Down Expand Up @@ -204,15 +204,15 @@ func (b *Bitstamp) GetTransactions(currencyPair string, values url.Values) ([]Tr
values,
)

return transactions, common.SendHTTPGetRequest(path, true, &transactions)
return transactions, common.SendHTTPGetRequest(path, true, b.Verbose, &transactions)
}

// GetEURUSDConversionRate returns the conversion rate between Euro and USD
func (b *Bitstamp) GetEURUSDConversionRate() (EURUSDConversionRate, error) {
rate := EURUSDConversionRate{}
path := fmt.Sprintf("%s/%s", bitstampAPIURL, bitstampAPIEURUSD)

return rate, common.SendHTTPGetRequest(path, true, &rate)
return rate, common.SendHTTPGetRequest(path, true, b.Verbose, &rate)
}

// GetBalance returns full balance of currency held on the exchange
Expand Down
2 changes: 1 addition & 1 deletion exchanges/bittrex/bittrex.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ func (b *Bittrex) HTTPRequest(path string, auth bool, values url.Values, v inter
return err
}
} else {
if err := common.SendHTTPGetRequest(path, true, &response); err != nil {
if err := common.SendHTTPGetRequest(path, true, b.Verbose, &response); err != nil {
return err
}
}
Expand Down
8 changes: 4 additions & 4 deletions exchanges/btcc/btcc.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (b *BTCC) GetTicker(currencyPair string) (Ticker, error) {
resp := Response{}
req := fmt.Sprintf("%sdata/ticker?market=%s", btccAPIUrl, currencyPair)

return resp.Ticker, common.SendHTTPGetRequest(req, true, &resp)
return resp.Ticker, common.SendHTTPGetRequest(req, true, b.Verbose, &resp)
}

// GetTradesLast24h returns the trades executed on the exchange over the past
Expand All @@ -109,7 +109,7 @@ func (b *BTCC) GetTradesLast24h(currencyPair string) ([]Trade, error) {
trades := []Trade{}
req := fmt.Sprintf("%sdata/trades?market=%s", btccAPIUrl, currencyPair)

return trades, common.SendHTTPGetRequest(req, true, &trades)
return trades, common.SendHTTPGetRequest(req, true, b.Verbose, &trades)
}

// GetTradeHistory returns trade history data
Expand All @@ -136,7 +136,7 @@ func (b *BTCC) GetTradeHistory(currencyPair string, limit, sinceTid int64, time

req = common.EncodeURLValues(req, v)

return trades, common.SendHTTPGetRequest(req, true, &trades)
return trades, common.SendHTTPGetRequest(req, true, b.Verbose, &trades)
}

// GetOrderBook returns current market order book
Expand All @@ -151,7 +151,7 @@ func (b *BTCC) GetOrderBook(currencyPair string, limit int) (Orderbook, error) {
req = fmt.Sprintf("%sdata/orderbook?market=%s", btccAPIUrl, currencyPair)
}

return result, common.SendHTTPGetRequest(req, true, &result)
return result, common.SendHTTPGetRequest(req, true, b.Verbose, &result)
}

func (b *BTCC) GetAccountInfo(infoType string) error {
Expand Down
6 changes: 3 additions & 3 deletions exchanges/btcmarkets/btcmarkets.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (b *BTCMarkets) GetTicker(symbol string) (Ticker, error) {
path := fmt.Sprintf("/market/%s/AUD/tick", common.StringToUpper(symbol))

return ticker,
common.SendHTTPGetRequest(btcMarketsAPIURL+path, true, &ticker)
common.SendHTTPGetRequest(btcMarketsAPIURL+path, true, b.Verbose, &ticker)
}

// GetOrderbook returns current orderbook
Expand All @@ -107,7 +107,7 @@ func (b *BTCMarkets) GetOrderbook(symbol string) (Orderbook, error) {
path := fmt.Sprintf("/market/%s/AUD/orderbook", common.StringToUpper(symbol))

return orderbook,
common.SendHTTPGetRequest(btcMarketsAPIURL+path, true, &orderbook)
common.SendHTTPGetRequest(btcMarketsAPIURL+path, true, b.Verbose, &orderbook)
}

// GetTrades returns executed trades on the exchange
Expand All @@ -117,7 +117,7 @@ func (b *BTCMarkets) GetTrades(symbol string, values url.Values) ([]Trade, error
trades := []Trade{}
path := common.EncodeURLValues(fmt.Sprintf("%s/market/%s/AUD/trades", btcMarketsAPIURL, symbol), values)

return trades, common.SendHTTPGetRequest(path, true, &trades)
return trades, common.SendHTTPGetRequest(path, true, b.Verbose, &trades)
}

// NewOrder requests a new order and returns an ID
Expand Down
18 changes: 9 additions & 9 deletions exchanges/gdax/gdax.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func (g *GDAX) GetProducts() ([]Product, error) {
products := []Product{}

return products,
common.SendHTTPGetRequest(gdaxAPIURL+gdaxProducts, true, &products)
common.SendHTTPGetRequest(gdaxAPIURL+gdaxProducts, true, g.Verbose, &products)
}

// GetOrderbook returns orderbook by currency pair and level
Expand All @@ -123,7 +123,7 @@ func (g *GDAX) GetOrderbook(symbol string, level int) (interface{}, error) {
path = fmt.Sprintf("%s/%s/%s?level=%s", gdaxAPIURL+gdaxProducts, symbol, gdaxOrderbook, levelStr)
}

if err := common.SendHTTPGetRequest(path, true, &orderbook); err != nil {
if err := common.SendHTTPGetRequest(path, true, g.Verbose, &orderbook); err != nil {
return nil, err
}

Expand Down Expand Up @@ -193,7 +193,7 @@ func (g *GDAX) GetTicker(currencyPair string) (Ticker, error) {
"%s/%s/%s", gdaxAPIURL+gdaxProducts, currencyPair, gdaxTicker)

log.Println(path)
return ticker, common.SendHTTPGetRequest(path, true, &ticker)
return ticker, common.SendHTTPGetRequest(path, true, g.Verbose, &ticker)
}

// GetTrades listd the latest trades for a product
Expand All @@ -203,7 +203,7 @@ func (g *GDAX) GetTrades(currencyPair string) ([]Trade, error) {
path := fmt.Sprintf(
"%s/%s/%s", gdaxAPIURL+gdaxProducts, currencyPair, gdaxTrades)

return trades, common.SendHTTPGetRequest(path, true, &trades)
return trades, common.SendHTTPGetRequest(path, true, g.Verbose, &trades)
}

// GetHistoricRates returns historic rates for a product. Rates are returned in
Expand All @@ -229,7 +229,7 @@ func (g *GDAX) GetHistoricRates(currencyPair string, start, end, granularity int
fmt.Sprintf("%s/%s/%s", gdaxAPIURL+gdaxProducts, currencyPair, gdaxHistory),
values)

if err := common.SendHTTPGetRequest(path, true, &resp); err != nil {
if err := common.SendHTTPGetRequest(path, true, g.Verbose, &resp); err != nil {
return history, err
}

Expand All @@ -255,7 +255,7 @@ func (g *GDAX) GetStats(currencyPair string) (Stats, error) {
path := fmt.Sprintf(
"%s/%s/%s", gdaxAPIURL+gdaxProducts, currencyPair, gdaxStats)

return stats, common.SendHTTPGetRequest(path, true, &stats)
return stats, common.SendHTTPGetRequest(path, true, g.Verbose, &stats)
}

// GetCurrencies returns a list of supported currency on the exchange
Expand All @@ -264,15 +264,15 @@ func (g *GDAX) GetCurrencies() ([]Currency, error) {
currencies := []Currency{}

return currencies,
common.SendHTTPGetRequest(gdaxAPIURL+gdaxCurrencies, true, &currencies)
common.SendHTTPGetRequest(gdaxAPIURL+gdaxCurrencies, true, g.Verbose, &currencies)
}

// GetServerTime returns the API server time
func (g *GDAX) GetServerTime() (ServerTime, error) {
serverTime := ServerTime{}

return serverTime,
common.SendHTTPGetRequest(gdaxAPIURL+gdaxTime, true, &serverTime)
common.SendHTTPGetRequest(gdaxAPIURL+gdaxTime, true, g.Verbose, &serverTime)
}

// GetAccounts returns a list of trading accounts associated with the APIKEYS
Expand Down Expand Up @@ -772,7 +772,7 @@ func (g *GDAX) SendAuthenticatedHTTPRequest(method, path string, params map[stri
}
}

nonce := g.Nonce.Evaluate()
nonce := g.Nonce.GetValue(g.Name, false).String()
message := nonce + method + "/" + path + string(payload)
hmac := common.GetHMAC(common.HashSHA256, []byte(message), []byte(g.APISecret))
headers := make(map[string]string)
Expand Down
Loading

0 comments on commit e8c7bf9

Please sign in to comment.