From 85393b59b81792a3925409b9079477a0d2dc48b0 Mon Sep 17 00:00:00 2001 From: Ryan O'Hara-Reid Date: Mon, 26 Feb 2018 16:31:41 +1100 Subject: [PATCH] Fixed linter issues for Poloniex exchange. --- exchanges/poloniex/poloniex.go | 237 ++++++++++++----------- exchanges/poloniex/poloniex_types.go | 160 ++++++++++----- exchanges/poloniex/poloniex_websocket.go | 52 ++--- exchanges/poloniex/poloniex_wrapper.go | 72 +++---- 4 files changed, 286 insertions(+), 235 deletions(-) diff --git a/exchanges/poloniex/poloniex.go b/exchanges/poloniex/poloniex.go index 3b1b1466..34171500 100644 --- a/exchanges/poloniex/poloniex.go +++ b/exchanges/poloniex/poloniex.go @@ -99,9 +99,9 @@ func (p *Poloniex) GetFee() float64 { } // GetTicker returns current ticker information -func (p *Poloniex) GetTicker() (map[string]PoloniexTicker, error) { +func (p *Poloniex) GetTicker() (map[string]Ticker, error) { type response struct { - Data map[string]PoloniexTicker + Data map[string]Ticker } resp := response{} @@ -119,17 +119,17 @@ func (p *Poloniex) GetVolume() (interface{}, error) { } // GetOrderbook returns the full orderbook from poloniex -func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (PoloniexOrderbookAll, error) { +func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (OrderbookAll, error) { vals := url.Values{} if depth != 0 { vals.Set("depth", strconv.Itoa(depth)) } - oba := PoloniexOrderbookAll{Data: make(map[string]PoloniexOrderbook)} + oba := OrderbookAll{Data: make(map[string]Orderbook)} if currencyPair != "" { vals.Set("currencyPair", currencyPair) - resp := PoloniexOrderbookResponse{} + resp := OrderbookResponse{} path := fmt.Sprintf("%s/public?command=returnOrderBook&%s", poloniexAPIURL, vals.Encode()) err := common.SendHTTPGetRequest(path, true, p.Verbose, &resp) if err != nil { @@ -139,7 +139,7 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (PoloniexOrderbo log.Println(resp.Error) return oba, fmt.Errorf("Poloniex GetOrderbook() error: %s", resp.Error) } - ob := PoloniexOrderbook{} + ob := Orderbook{} for x := range resp.Asks { data := resp.Asks[x] price, err := strconv.ParseFloat(data[0].(string), 64) @@ -147,7 +147,7 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (PoloniexOrderbo return oba, err } amount := data[1].(float64) - ob.Asks = append(ob.Asks, PoloniexOrderbookItem{Price: price, Amount: amount}) + ob.Asks = append(ob.Asks, OrderbookItem{Price: price, Amount: amount}) } for x := range resp.Bids { @@ -157,19 +157,19 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (PoloniexOrderbo return oba, err } amount := data[1].(float64) - ob.Bids = append(ob.Bids, PoloniexOrderbookItem{Price: price, Amount: amount}) + ob.Bids = append(ob.Bids, OrderbookItem{Price: price, Amount: amount}) } - oba.Data[currencyPair] = PoloniexOrderbook{Bids: ob.Bids, Asks: ob.Asks} + oba.Data[currencyPair] = Orderbook{Bids: ob.Bids, Asks: ob.Asks} } else { vals.Set("currencyPair", "all") - resp := PoloniexOrderbookResponseAll{} + resp := OrderbookResponseAll{} path := fmt.Sprintf("%s/public?command=returnOrderBook&%s", poloniexAPIURL, vals.Encode()) err := common.SendHTTPGetRequest(path, true, p.Verbose, &resp.Data) if err != nil { return oba, err } for currency, orderbook := range resp.Data { - ob := PoloniexOrderbook{} + ob := Orderbook{} for x := range orderbook.Asks { data := orderbook.Asks[x] price, err := strconv.ParseFloat(data[0].(string), 64) @@ -177,7 +177,7 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (PoloniexOrderbo return oba, err } amount := data[1].(float64) - ob.Asks = append(ob.Asks, PoloniexOrderbookItem{Price: price, Amount: amount}) + ob.Asks = append(ob.Asks, OrderbookItem{Price: price, Amount: amount}) } for x := range orderbook.Bids { @@ -187,16 +187,16 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (PoloniexOrderbo return oba, err } amount := data[1].(float64) - ob.Bids = append(ob.Bids, PoloniexOrderbookItem{Price: price, Amount: amount}) + ob.Bids = append(ob.Bids, OrderbookItem{Price: price, Amount: amount}) } - oba.Data[currency] = PoloniexOrderbook{Bids: ob.Bids, Asks: ob.Asks} + oba.Data[currency] = Orderbook{Bids: ob.Bids, Asks: ob.Asks} } } return oba, nil } // GetTradeHistory returns trades history from poloniex -func (p *Poloniex) GetTradeHistory(currencyPair, start, end string) ([]PoloniexTradeHistory, error) { +func (p *Poloniex) GetTradeHistory(currencyPair, start, end string) ([]TradeHistory, error) { vals := url.Values{} vals.Set("currencyPair", currencyPair) @@ -208,14 +208,14 @@ func (p *Poloniex) GetTradeHistory(currencyPair, start, end string) ([]PoloniexT vals.Set("end", end) } - resp := []PoloniexTradeHistory{} + resp := []TradeHistory{} path := fmt.Sprintf("%s/public?command=returnTradeHistory&%s", poloniexAPIURL, vals.Encode()) return resp, common.SendHTTPGetRequest(path, true, p.Verbose, &resp) } // GetChartData returns chart data for a specific currency pair -func (p *Poloniex) GetChartData(currencyPair, start, end, period string) ([]PoloniexChartData, error) { +func (p *Poloniex) GetChartData(currencyPair, start, end, period string) ([]ChartData, error) { vals := url.Values{} vals.Set("currencyPair", currencyPair) @@ -231,7 +231,7 @@ func (p *Poloniex) GetChartData(currencyPair, start, end, period string) ([]Polo vals.Set("period", period) } - resp := []PoloniexChartData{} + resp := []ChartData{} path := fmt.Sprintf("%s/public?command=returnChartData&%s", poloniexAPIURL, vals.Encode()) err := common.SendHTTPGetRequest(path, true, p.Verbose, &resp) @@ -243,9 +243,9 @@ func (p *Poloniex) GetChartData(currencyPair, start, end, period string) ([]Polo } // GetCurrencies returns information about currencies -func (p *Poloniex) GetCurrencies() (map[string]PoloniexCurrencies, error) { +func (p *Poloniex) GetCurrencies() (map[string]Currencies, error) { type Response struct { - Data map[string]PoloniexCurrencies + Data map[string]Currencies } resp := Response{} path := fmt.Sprintf("%s/public?command=returnCurrencies", poloniexAPIURL) @@ -271,23 +271,24 @@ func (p *Poloniex) GetExchangeCurrencies() ([]string, error) { // GetLoanOrders returns the list of loan offers and demands for a given // currency, specified by the "currency" GET parameter. -func (p *Poloniex) GetLoanOrders(currency string) (PoloniexLoanOrders, error) { - resp := PoloniexLoanOrders{} +func (p *Poloniex) GetLoanOrders(currency string) (LoanOrders, error) { + resp := LoanOrders{} path := fmt.Sprintf("%s/public?command=returnLoanOrders¤cy=%s", poloniexAPIURL, currency) return resp, common.SendHTTPGetRequest(path, true, p.Verbose, &resp) } -func (p *Poloniex) GetBalances() (PoloniexBalance, error) { +// GetBalances returns balances for your account. +func (p *Poloniex) GetBalances() (Balance, error) { var result interface{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexBalances, url.Values{}, &result) if err != nil { - return PoloniexBalance{}, err + return Balance{}, err } data := result.(map[string]interface{}) - balance := PoloniexBalance{} + balance := Balance{} balance.Currency = make(map[string]float64) for x, y := range data { @@ -297,25 +298,22 @@ func (p *Poloniex) GetBalances() (PoloniexBalance, error) { return balance, nil } -type PoloniexCompleteBalances struct { - Currency map[string]PoloniexCompleteBalance -} - -func (p *Poloniex) GetCompleteBalances() (PoloniexCompleteBalances, error) { +// GetCompleteBalances returns complete balances from your account. +func (p *Poloniex) GetCompleteBalances() (CompleteBalances, error) { var result interface{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexBalancesComplete, url.Values{}, &result) if err != nil { - return PoloniexCompleteBalances{}, err + return CompleteBalances{}, err } data := result.(map[string]interface{}) - balance := PoloniexCompleteBalances{} - balance.Currency = make(map[string]PoloniexCompleteBalance) + balance := CompleteBalances{} + balance.Currency = make(map[string]CompleteBalance) for x, y := range data { dataVals := y.(map[string]interface{}) - balancesData := PoloniexCompleteBalance{} + balancesData := CompleteBalance{} balancesData.Available, _ = strconv.ParseFloat(dataVals["available"].(string), 64) balancesData.OnOrders, _ = strconv.ParseFloat(dataVals["onOrders"].(string), 64) balancesData.BTCValue, _ = strconv.ParseFloat(dataVals["btcValue"].(string), 64) @@ -325,9 +323,10 @@ func (p *Poloniex) GetCompleteBalances() (PoloniexCompleteBalances, error) { return balance, nil } -func (p *Poloniex) GetDepositAddresses() (PoloniexDepositAddresses, error) { +// GetDepositAddresses returns deposit addresses for all enabled cryptos. +func (p *Poloniex) GetDepositAddresses() (DepositAddresses, error) { var result interface{} - addresses := PoloniexDepositAddresses{} + addresses := DepositAddresses{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexDepositAddresses, url.Values{}, &result) if err != nil { @@ -343,6 +342,7 @@ func (p *Poloniex) GetDepositAddresses() (PoloniexDepositAddresses, error) { return addresses, nil } +// GenerateNewAddress generates a new address for a currency func (p *Poloniex) GenerateNewAddress(currency string) (string, error) { type Response struct { Success int @@ -366,8 +366,9 @@ func (p *Poloniex) GenerateNewAddress(currency string) (string, error) { return resp.Response, nil } -func (p *Poloniex) GetDepositsWithdrawals(start, end string) (PoloniexDepositsWithdrawals, error) { - resp := PoloniexDepositsWithdrawals{} +// GetDepositsWithdrawals returns a list of deposits and withdrawals +func (p *Poloniex) GetDepositsWithdrawals(start, end string) (DepositsWithdrawals, error) { + resp := DepositsWithdrawals{} values := url.Values{} if start != "" { @@ -391,32 +392,33 @@ func (p *Poloniex) GetDepositsWithdrawals(start, end string) (PoloniexDepositsWi return resp, nil } +// GetOpenOrders returns current unfilled opened orders func (p *Poloniex) GetOpenOrders(currency string) (interface{}, error) { values := url.Values{} if currency != "" { values.Set("currencyPair", currency) - result := PoloniexOpenOrdersResponse{} + result := OpenOrdersResponse{} + err := p.SendAuthenticatedHTTPRequest("POST", poloniexOrders, values, &result.Data) - - if err != nil { - return result, err - } - - return result, nil - } else { - values.Set("currencyPair", "all") - result := PoloniexOpenOrdersResponseAll{} - err := p.SendAuthenticatedHTTPRequest("POST", poloniexOrders, values, &result.Data) - if err != nil { return result, err } return result, nil } + values.Set("currencyPair", "all") + result := OpenOrdersResponseAll{} + + err := p.SendAuthenticatedHTTPRequest("POST", poloniexOrders, values, &result.Data) + if err != nil { + return result, err + } + + return result, nil } +// GetAuthenticatedTradeHistory returns account trade history func (p *Poloniex) GetAuthenticatedTradeHistory(currency, start, end, limit string) (interface{}, error) { values := url.Values{} @@ -434,29 +436,29 @@ func (p *Poloniex) GetAuthenticatedTradeHistory(currency, start, end, limit stri if currency != "" && currency != "all" { values.Set("currencyPair", currency) - result := PoloniexAuthenticatedTradeHistoryResponse{} + result := AuthenticatedTradeHistoryResponse{} + err := p.SendAuthenticatedHTTPRequest("POST", poloniexTradeHistory, values, &result.Data) - - if err != nil { - return result, err - } - - return result, nil - } else { - values.Set("currencyPair", "all") - result := PoloniexAuthenticatedTradeHistoryAll{} - err := p.SendAuthenticatedHTTPRequest("POST", poloniexTradeHistory, values, &result.Data) - if err != nil { return result, err } return result, nil } + values.Set("currencyPair", "all") + result := AuthenticatedTradeHistoryAll{} + + err := p.SendAuthenticatedHTTPRequest("POST", poloniexTradeHistory, values, &result.Data) + if err != nil { + return result, err + } + + return result, nil } -func (p *Poloniex) PlaceOrder(currency string, rate, amount float64, immediate, fillOrKill, buy bool) (PoloniexOrderResponse, error) { - result := PoloniexOrderResponse{} +// PlaceOrder places a new order on the exchange +func (p *Poloniex) PlaceOrder(currency string, rate, amount float64, immediate, fillOrKill, buy bool) (OrderResponse, error) { + result := OrderResponse{} values := url.Values{} var orderType string @@ -487,8 +489,9 @@ func (p *Poloniex) PlaceOrder(currency string, rate, amount float64, immediate, return result, nil } +// CancelOrder cancels and order by orderID func (p *Poloniex) CancelOrder(orderID int64) (bool, error) { - result := PoloniexGenericResponse{} + result := GenericResponse{} values := url.Values{} values.Set("orderNumber", strconv.FormatInt(orderID, 10)) @@ -505,8 +508,9 @@ func (p *Poloniex) CancelOrder(orderID int64) (bool, error) { return true, nil } -func (p *Poloniex) MoveOrder(orderID int64, rate, amount float64) (PoloniexMoveOrderResponse, error) { - result := PoloniexMoveOrderResponse{} +// MoveOrder moves an order +func (p *Poloniex) MoveOrder(orderID int64, rate, amount float64) (MoveOrderResponse, error) { + result := MoveOrderResponse{} values := url.Values{} values.Set("orderNumber", strconv.FormatInt(orderID, 10)) values.Set("rate", strconv.FormatFloat(rate, 'f', -1, 64)) @@ -528,8 +532,9 @@ func (p *Poloniex) MoveOrder(orderID int64, rate, amount float64) (PoloniexMoveO return result, nil } +// Withdraw withdraws a currency to a specific delegated address func (p *Poloniex) Withdraw(currency, address string, amount float64) (bool, error) { - result := PoloniexWithdraw{} + result := Withdraw{} values := url.Values{} values.Set("currency", currency) @@ -549,17 +554,14 @@ func (p *Poloniex) Withdraw(currency, address string, amount float64) (bool, err return true, nil } -func (p *Poloniex) GetFeeInfo() (PoloniexFee, error) { - result := PoloniexFee{} - err := p.SendAuthenticatedHTTPRequest("POST", poloniexFeeInfo, url.Values{}, &result) +// GetFeeInfo returns fee information +func (p *Poloniex) GetFeeInfo() (Fee, error) { + result := Fee{} - if err != nil { - return result, err - } - - return result, nil + return result, p.SendAuthenticatedHTTPRequest("POST", poloniexFeeInfo, url.Values{}, &result) } +// GetTradableBalances returns tradable balances func (p *Poloniex) GetTradableBalances() (map[string]map[string]float64, error) { type Response struct { Data map[string]map[string]interface{} @@ -584,9 +586,10 @@ func (p *Poloniex) GetTradableBalances() (map[string]map[string]float64, error) return balances, nil } +// TransferBalance transfers balances between your accounts func (p *Poloniex) TransferBalance(currency, from, to string, amount float64) (bool, error) { values := url.Values{} - result := PoloniexGenericResponse{} + result := GenericResponse{} values.Set("currency", currency) values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64)) @@ -606,8 +609,9 @@ func (p *Poloniex) TransferBalance(currency, from, to string, amount float64) (b return true, nil } -func (p *Poloniex) GetMarginAccountSummary() (PoloniexMargin, error) { - result := PoloniexMargin{} +// GetMarginAccountSummary returns a summary on your margin accounts +func (p *Poloniex) GetMarginAccountSummary() (Margin, error) { + result := Margin{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexMarginAccountSummary, url.Values{}, &result) if err != nil { @@ -617,8 +621,9 @@ func (p *Poloniex) GetMarginAccountSummary() (PoloniexMargin, error) { return result, nil } -func (p *Poloniex) PlaceMarginOrder(currency string, rate, amount, lendingRate float64, buy bool) (PoloniexOrderResponse, error) { - result := PoloniexOrderResponse{} +// PlaceMarginOrder places a margin order +func (p *Poloniex) PlaceMarginOrder(currency string, rate, amount, lendingRate float64, buy bool) (OrderResponse, error) { + result := OrderResponse{} values := url.Values{} var orderType string @@ -645,41 +650,41 @@ func (p *Poloniex) PlaceMarginOrder(currency string, rate, amount, lendingRate f return result, nil } +// GetMarginPosition returns a position on a margin order func (p *Poloniex) GetMarginPosition(currency string) (interface{}, error) { values := url.Values{} if currency != "" && currency != "all" { values.Set("currencyPair", currency) - result := PoloniexMarginPosition{} + result := MarginPosition{} + err := p.SendAuthenticatedHTTPRequest("POST", poloniexMarginPosition, values, &result) - - if err != nil { - return result, err - } - - return result, nil - } else { - values.Set("currencyPair", "all") - - type Response struct { - Data map[string]PoloniexMarginPosition - } - - result := Response{} - err := p.SendAuthenticatedHTTPRequest("POST", poloniexMarginPosition, values, &result.Data) - if err != nil { return result, err } return result, nil } + values.Set("currencyPair", "all") + + type Response struct { + Data map[string]MarginPosition + } + result := Response{} + + err := p.SendAuthenticatedHTTPRequest("POST", poloniexMarginPosition, values, &result.Data) + if err != nil { + return result, err + } + + return result, nil } +// CloseMarginPosition closes a current margin position func (p *Poloniex) CloseMarginPosition(currency string) (bool, error) { values := url.Values{} values.Set("currencyPair", currency) - result := PoloniexGenericResponse{} + result := GenericResponse{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexMarginPositionClose, values, &result) @@ -694,6 +699,7 @@ func (p *Poloniex) CloseMarginPosition(currency string) (bool, error) { return true, nil } +// CreateLoanOffer places a loan offer on the exchange func (p *Poloniex) CreateLoanOffer(currency string, amount, rate float64, duration int, autoRenew bool) (int64, error) { values := url.Values{} values.Set("currency", currency) @@ -729,8 +735,9 @@ func (p *Poloniex) CreateLoanOffer(currency string, amount, rate float64, durati return result.OrderID, nil } +// CancelLoanOffer cancels a loan offer order func (p *Poloniex) CancelLoanOffer(orderNumber int64) (bool, error) { - result := PoloniexGenericResponse{} + result := GenericResponse{} values := url.Values{} values.Set("orderID", strconv.FormatInt(orderNumber, 10)) @@ -747,9 +754,10 @@ func (p *Poloniex) CancelLoanOffer(orderNumber int64) (bool, error) { return true, nil } -func (p *Poloniex) GetOpenLoanOffers() (map[string][]PoloniexLoanOffer, error) { +// GetOpenLoanOffers returns all open loan offers +func (p *Poloniex) GetOpenLoanOffers() (map[string][]LoanOffer, error) { type Response struct { - Data map[string][]PoloniexLoanOffer + Data map[string][]LoanOffer } result := Response{} @@ -760,14 +768,15 @@ func (p *Poloniex) GetOpenLoanOffers() (map[string][]PoloniexLoanOffer, error) { } if result.Data == nil { - return nil, errors.New("There are no open loan offers.") + return nil, errors.New("there are no open loan offers") } return result.Data, nil } -func (p *Poloniex) GetActiveLoans() (PoloniexActiveLoans, error) { - result := PoloniexActiveLoans{} +// GetActiveLoans returns active loans +func (p *Poloniex) GetActiveLoans() (ActiveLoans, error) { + result := ActiveLoans{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexActiveLoans, url.Values{}, &result) if err != nil { @@ -777,7 +786,8 @@ func (p *Poloniex) GetActiveLoans() (PoloniexActiveLoans, error) { return result, nil } -func (p *Poloniex) GetLendingHistory(start, end string) ([]PoloniexLendingHistory, error) { +// GetLendingHistory returns lending history for the account +func (p *Poloniex) GetLendingHistory(start, end string) ([]LendingHistory, error) { vals := url.Values{} if start != "" { @@ -788,7 +798,7 @@ func (p *Poloniex) GetLendingHistory(start, end string) ([]PoloniexLendingHistor vals.Set("end", end) } - resp := []PoloniexLendingHistory{} + resp := []LendingHistory{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexLendingHistory, vals, &resp) if err != nil { @@ -797,10 +807,11 @@ func (p *Poloniex) GetLendingHistory(start, end string) ([]PoloniexLendingHistor return resp, nil } +// ToggleAutoRenew allows for the autorenew of a contract func (p *Poloniex) ToggleAutoRenew(orderNumber int64) (bool, error) { values := url.Values{} values.Set("orderNumber", strconv.FormatInt(orderNumber, 10)) - result := PoloniexGenericResponse{} + result := GenericResponse{} err := p.SendAuthenticatedHTTPRequest("POST", poloniexAutoRenew, values, &result) @@ -815,6 +826,7 @@ func (p *Poloniex) ToggleAutoRenew(orderNumber int64) (bool, error) { return true, nil } +// SendAuthenticatedHTTPRequest sends an authenticated HTTP request func (p *Poloniex) SendAuthenticatedHTTPRequest(method, endpoint string, values url.Values, result interface{}) error { if !p.AuthenticatedAPISupport { return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, p.Name) @@ -835,16 +847,11 @@ func (p *Poloniex) SendAuthenticatedHTTPRequest(method, endpoint string, values headers["Sign"] = common.HexEncodeToString(hmac) path := fmt.Sprintf("%s/%s", poloniexAPIURL, poloniexAPITradingEndpoint) - resp, err := common.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 = common.JSONDecode([]byte(resp), &result) - - if err != nil { - return errors.New("Unable to JSON Unmarshal response.") - } - return nil + return common.JSONDecode([]byte(resp), &result) } diff --git a/exchanges/poloniex/poloniex_types.go b/exchanges/poloniex/poloniex_types.go index 6b747d54..9e0ad507 100644 --- a/exchanges/poloniex/poloniex_types.go +++ b/exchanges/poloniex/poloniex_types.go @@ -1,6 +1,7 @@ package poloniex -type PoloniexTicker struct { +// Ticker holds ticker data +type Ticker struct { Last float64 `json:"last,string"` LowestAsk float64 `json:"lowestAsk,string"` HighestBid float64 `json:"highestBid,string"` @@ -12,32 +13,43 @@ type PoloniexTicker struct { Low24Hr float64 `json:"low24hr,string"` } -type PoloniexOrderbookResponseAll struct { - Data map[string]PoloniexOrderbookResponse +// OrderbookResponseAll holds the full response type orderbook +type OrderbookResponseAll struct { + Data map[string]OrderbookResponse } -type PoloniexOrderbookResponse struct { +// CompleteBalances holds the full balance data +type CompleteBalances struct { + Currency map[string]CompleteBalance +} + +// OrderbookResponse is a sub-type for orderbooks +type OrderbookResponse struct { Asks [][]interface{} `json:"asks"` Bids [][]interface{} `json:"bids"` IsFrozen string `json:"isFrozen"` Error string `json:"error"` } -type PoloniexOrderbookItem struct { +// OrderbookItem holds data on an individual item +type OrderbookItem struct { Price float64 Amount float64 } -type PoloniexOrderbookAll struct { - Data map[string]PoloniexOrderbook +// OrderbookAll contains the full range of orderbooks +type OrderbookAll struct { + Data map[string]Orderbook } -type PoloniexOrderbook struct { - Asks []PoloniexOrderbookItem `json:"asks"` - Bids []PoloniexOrderbookItem `json:"bids"` +// Orderbook is a generic type golding orderbook information +type Orderbook struct { + Asks []OrderbookItem `json:"asks"` + Bids []OrderbookItem `json:"bids"` } -type PoloniexTradeHistory struct { +// TradeHistory holds trade history data +type TradeHistory struct { GlobalTradeID int64 `json:"globalTradeID"` TradeID int64 `json:"tradeID"` Date string `json:"date"` @@ -47,7 +59,8 @@ type PoloniexTradeHistory struct { Total float64 `json:"total,string"` } -type PoloniexChartData struct { +// ChartData holds kline data +type ChartData struct { Date int `json:"date"` High float64 `json:"high"` Low float64 `json:"low"` @@ -59,7 +72,8 @@ type PoloniexChartData struct { Error string `json:"error"` } -type PoloniexCurrencies struct { +// Currencies contains currency information +type Currencies struct { Name string `json:"name"` MaxDailyWithdrawal string `json:"maxDailyWithdrawal"` TxFee float64 `json:"txFee,string"` @@ -70,33 +84,39 @@ type PoloniexCurrencies struct { Frozen int `json:"frozen"` } -type PoloniexLoanOrder struct { +// LoanOrder holds loan order information +type LoanOrder struct { Rate float64 `json:"rate,string"` Amount float64 `json:"amount,string"` RangeMin int `json:"rangeMin"` RangeMax int `json:"rangeMax"` } -type PoloniexLoanOrders struct { - Offers []PoloniexLoanOrder `json:"offers"` - Demands []PoloniexLoanOrder `json:"demands"` +// LoanOrders holds loan order information range +type LoanOrders struct { + Offers []LoanOrder `json:"offers"` + Demands []LoanOrder `json:"demands"` } -type PoloniexBalance struct { +// Balance holds data for a range of currencies +type Balance struct { Currency map[string]float64 } -type PoloniexCompleteBalance struct { +// CompleteBalance contains the complete balance with a btcvalue +type CompleteBalance struct { Available float64 OnOrders float64 BTCValue float64 } -type PoloniexDepositAddresses struct { +// DepositAddresses holds the full address per crypto-currency +type DepositAddresses struct { Addresses map[string]string } -type PoloniexDepositsWithdrawals struct { +// DepositsWithdrawals holds withdrawal information +type DepositsWithdrawals struct { Deposits []struct { Currency string `json:"currency"` Address string `json:"address"` @@ -119,7 +139,8 @@ type PoloniexDepositsWithdrawals struct { } `json:"withdrawals"` } -type PoloniexOrder struct { +// Order hold order information +type Order struct { OrderNumber int64 `json:"orderNumber,string"` Type string `json:"type"` Rate float64 `json:"rate,string"` @@ -129,15 +150,18 @@ type PoloniexOrder struct { Margin float64 `json:"margin"` } -type PoloniexOpenOrdersResponseAll struct { - Data map[string][]PoloniexOrder +// OpenOrdersResponseAll holds all open order responses +type OpenOrdersResponseAll struct { + Data map[string][]Order } -type PoloniexOpenOrdersResponse struct { - Data []PoloniexOrder +// OpenOrdersResponse holds open response orders +type OpenOrdersResponse struct { + Data []Order } -type PoloniexAuthentictedTradeHistory struct { +// AuthentictedTradeHistory holds client trade history information +type AuthentictedTradeHistory struct { GlobalTradeID int64 `json:"globalTradeID"` TradeID int64 `json:"tradeID,string"` Date string `json:"date"` @@ -150,15 +174,18 @@ type PoloniexAuthentictedTradeHistory struct { Category string `json:"category"` } -type PoloniexAuthenticatedTradeHistoryAll struct { - Data map[string][]PoloniexAuthentictedTradeHistory +// AuthenticatedTradeHistoryAll holds the full client trade history +type AuthenticatedTradeHistoryAll struct { + Data map[string][]AuthentictedTradeHistory } -type PoloniexAuthenticatedTradeHistoryResponse struct { - Data []PoloniexAuthentictedTradeHistory +// AuthenticatedTradeHistoryResponse is a response type for trade history +type AuthenticatedTradeHistoryResponse struct { + Data []AuthentictedTradeHistory } -type PoloniexResultingTrades struct { +// ResultingTrades holds resultant trade information +type ResultingTrades struct { Amount float64 `json:"amount,string"` Date string `json:"date"` Rate float64 `json:"rate,string"` @@ -167,36 +194,42 @@ type PoloniexResultingTrades struct { Type string `json:"type"` } -type PoloniexOrderResponse struct { - OrderNumber int64 `json:"orderNumber,string"` - Trades []PoloniexResultingTrades `json:"resultingTrades"` +// OrderResponse is a response type of trades +type OrderResponse struct { + OrderNumber int64 `json:"orderNumber,string"` + Trades []ResultingTrades `json:"resultingTrades"` } -type PoloniexGenericResponse struct { +// GenericResponse is a response type for exchange generic responses +type GenericResponse struct { Success int `json:"success"` Error string `json:"error"` } -type PoloniexMoveOrderResponse struct { - Success int `json:"success"` - Error string `json:"error"` - OrderNumber int64 `json:"orderNumber,string"` - Trades map[string][]PoloniexResultingTrades `json:"resultingTrades"` +// MoveOrderResponse is a response type for move order trades +type MoveOrderResponse struct { + Success int `json:"success"` + Error string `json:"error"` + OrderNumber int64 `json:"orderNumber,string"` + Trades map[string][]ResultingTrades `json:"resultingTrades"` } -type PoloniexWithdraw struct { +// Withdraw holds withdraw information +type Withdraw struct { Response string `json:"response"` Error string `json:"error"` } -type PoloniexFee struct { +// Fee holds fees for specific trades +type Fee struct { MakerFee float64 `json:"makerFee,string"` TakerFee float64 `json:"takerFee,string"` ThirtyDayVolume float64 `json:"thirtyDayVolume,string"` NextTier float64 `json:"nextTier,string"` } -type PoloniexMargin struct { +// Margin holds margin information +type Margin struct { TotalValue float64 `json:"totalValue,string"` ProfitLoss float64 `json:"pl,string"` LendingFees float64 `json:"lendingFees,string"` @@ -205,7 +238,8 @@ type PoloniexMargin struct { CurrentMargin float64 `json:"currentMargin,string"` } -type PoloniexMarginPosition struct { +// MarginPosition holds margin positional information +type MarginPosition struct { Amount float64 `json:"amount,string"` Total float64 `json:"total,string"` BasePrice float64 `json:"basePrice,string"` @@ -215,7 +249,8 @@ type PoloniexMarginPosition struct { Type string `json:"type"` } -type PoloniexLoanOffer struct { +// LoanOffer holds loan offer information +type LoanOffer struct { ID int64 `json:"id"` Rate float64 `json:"rate,string"` Amount float64 `json:"amount,string"` @@ -224,12 +259,14 @@ type PoloniexLoanOffer struct { Date string `json:"date"` } -type PoloniexActiveLoans struct { - Provided []PoloniexLoanOffer `json:"provided"` - Used []PoloniexLoanOffer `json:"used"` +// ActiveLoans shows the full active loans on the exchange +type ActiveLoans struct { + Provided []LoanOffer `json:"provided"` + Used []LoanOffer `json:"used"` } -type PoloniexLendingHistory struct { +// LendingHistory holds the full lending history data +type LendingHistory struct { ID int64 `json:"id"` Currency string `json:"currency"` Rate float64 `json:"rate,string"` @@ -241,3 +278,26 @@ type PoloniexLendingHistory struct { Open string `json:"open"` Close string `json:"close"` } + +// WebsocketTicker holds ticker data for the websocket +type WebsocketTicker struct { + CurrencyPair string + Last float64 + LowestAsk float64 + HighestBid float64 + PercentChange float64 + BaseVolume float64 + QuoteVolume float64 + IsFrozen bool + High float64 + Low float64 +} + +// WebsocketTrollboxMessage holds trollbox messages and information for +// websocket +type WebsocketTrollboxMessage struct { + MessageNumber float64 + Username string + Message string + Reputation float64 +} diff --git a/exchanges/poloniex/poloniex_websocket.go b/exchanges/poloniex/poloniex_websocket.go index 4c2291e7..1db5eeee 100644 --- a/exchanges/poloniex/poloniex_websocket.go +++ b/exchanges/poloniex/poloniex_websocket.go @@ -8,27 +8,15 @@ import ( ) const ( - POLONIEX_WEBSOCKET_ADDRESS = "wss://api.poloniex.com" - POLONIEX_WEBSOCKET_REALM = "realm1" - POLONIEX_WEBSOCKET_TICKER = "ticker" - POLONIEX_WEBSOCKET_TROLLBOX = "trollbox" + poloniexWebsocketAddress = "wss://api.poloniex.com" + poloniexWebsocketRealm = "realm1" + poloniexWebsocketTicker = "ticker" + poloniexWebsocketTrollbox = "trollbox" ) -type PoloniexWebsocketTicker struct { - CurrencyPair string - Last float64 - LowestAsk float64 - HighestBid float64 - PercentChange float64 - BaseVolume float64 - QuoteVolume float64 - IsFrozen bool - High float64 - Low float64 -} - -func PoloniexOnTicker(args []interface{}, kwargs map[string]interface{}) { - ticker := PoloniexWebsocketTicker{} +// OnTicker converts ticker data to a websocketTicker +func OnTicker(args []interface{}, kwargs map[string]interface{}) { + ticker := WebsocketTicker{} ticker.CurrencyPair = args[0].(string) ticker.Last, _ = strconv.ParseFloat(args[1].(string), 64) ticker.LowestAsk, _ = strconv.ParseFloat(args[2].(string), 64) @@ -47,15 +35,9 @@ func PoloniexOnTicker(args []interface{}, kwargs map[string]interface{}) { ticker.Low, _ = strconv.ParseFloat(args[9].(string), 64) } -type PoloniexWebsocketTrollboxMessage struct { - MessageNumber float64 - Username string - Message string - Reputation float64 -} - -func PoloniexOnTrollbox(args []interface{}, kwargs map[string]interface{}) { - message := PoloniexWebsocketTrollboxMessage{} +// OnTrollbox handles trollbox messages +func OnTrollbox(args []interface{}, kwargs map[string]interface{}) { + message := WebsocketTrollboxMessage{} message.MessageNumber, _ = args[1].(float64) message.Username = args[2].(string) message.Message = args[3].(string) @@ -64,7 +46,8 @@ func PoloniexOnTrollbox(args []interface{}, kwargs map[string]interface{}) { } } -func PoloniexOnDepthOrTrade(args []interface{}, kwargs map[string]interface{}) { +// OnDepthOrTrade handles orderbook depth and trade events +func OnDepthOrTrade(args []interface{}, kwargs map[string]interface{}) { for x := range args { data := args[x].(map[string]interface{}) msgData := data["data"].(map[string]interface{}) @@ -133,9 +116,10 @@ func PoloniexOnDepthOrTrade(args []interface{}, kwargs map[string]interface{}) { } } +// WebsocketClient creates a new websocket client func (p *Poloniex) WebsocketClient() { for p.Enabled && p.Websocket { - c, err := turnpike.NewWebsocketClient(turnpike.JSON, POLONIEX_WEBSOCKET_ADDRESS, nil) + c, err := turnpike.NewWebsocketClient(turnpike.JSON, poloniexWebsocketAddress, nil) if err != nil { log.Printf("%s Unable to connect to Websocket. Error: %s\n", p.GetName(), err) continue @@ -145,7 +129,7 @@ func (p *Poloniex) WebsocketClient() { log.Printf("%s Connected to Websocket.\n", p.GetName()) } - _, err = c.JoinRealm(POLONIEX_WEBSOCKET_REALM, nil) + _, err = c.JoinRealm(poloniexWebsocketRealm, nil) if err != nil { log.Printf("%s Unable to join realm. Error: %s\n", p.GetName(), err) continue @@ -157,17 +141,17 @@ func (p *Poloniex) WebsocketClient() { c.ReceiveDone = make(chan bool) - if err := c.Subscribe(POLONIEX_WEBSOCKET_TICKER, PoloniexOnTicker); err != nil { + if err := c.Subscribe(poloniexWebsocketTicker, OnTicker); err != nil { log.Printf("%s Error subscribing to ticker channel: %s\n", p.GetName(), err) } - if err := c.Subscribe(POLONIEX_WEBSOCKET_TROLLBOX, PoloniexOnTrollbox); err != nil { + if err := c.Subscribe(poloniexWebsocketTrollbox, OnTrollbox); err != nil { log.Printf("%s Error subscribing to trollbox channel: %s\n", p.GetName(), err) } for x := range p.EnabledPairs { currency := p.EnabledPairs[x] - if err := c.Subscribe(currency, PoloniexOnDepthOrTrade); err != nil { + if err := c.Subscribe(currency, OnDepthOrTrade); err != nil { log.Printf("%s Error subscribing to %s channel: %s\n", p.GetName(), currency, err) } } diff --git a/exchanges/poloniex/poloniex_wrapper.go b/exchanges/poloniex/poloniex_wrapper.go index b27e2f8f..dc0b6eb1 100644 --- a/exchanges/poloniex/poloniex_wrapper.go +++ b/exchanges/poloniex/poloniex_wrapper.go @@ -12,50 +12,50 @@ import ( ) // Start starts the Poloniex go routine -func (p *Poloniex) Start() { - go p.Run() +func (po *Poloniex) Start() { + go po.Run() } // Run implements the Poloniex wrapper -func (p *Poloniex) Run() { - if p.Verbose { - 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) +func (po *Poloniex) Run() { + if po.Verbose { + log.Printf("%s Websocket: %s (url: %s).\n", po.GetName(), common.IsEnabled(po.Websocket), poloniexWebsocketAddress) + log.Printf("%s polling delay: %ds.\n", po.GetName(), po.RESTPollingDelay) + log.Printf("%s %d currencies enabled: %s.\n", po.GetName(), len(po.EnabledPairs), po.EnabledPairs) } - if p.Websocket { - go p.WebsocketClient() + if po.Websocket { + go po.WebsocketClient() } - exchangeCurrencies, err := p.GetExchangeCurrencies() + exchangeCurrencies, err := po.GetExchangeCurrencies() if err != nil { - log.Printf("%s Failed to get available symbols.\n", p.GetName()) + log.Printf("%s Failed to get available symbols.\n", po.GetName()) } else { forceUpdate := false - if common.StringDataCompare(p.AvailablePairs, "BTC_USDT") { + if common.StringDataCompare(po.AvailablePairs, "BTC_USDT") { log.Printf("%s contains invalid pair, forcing upgrade of available currencies.\n", - p.GetName()) + po.GetName()) forceUpdate = true } - err = p.UpdateAvailableCurrencies(exchangeCurrencies, forceUpdate) + err = po.UpdateAvailableCurrencies(exchangeCurrencies, forceUpdate) if err != nil { - log.Printf("%s Failed to update available currencies %s.\n", p.GetName(), err) + log.Printf("%s Failed to update available currencies %s.\n", po.GetName(), err) } } } // UpdateTicker updates and returns the ticker for a currency pair -func (p *Poloniex) UpdateTicker(currencyPair pair.CurrencyPair, assetType string) (ticker.Price, error) { +func (po *Poloniex) UpdateTicker(currencyPair pair.CurrencyPair, assetType string) (ticker.Price, error) { var tickerPrice ticker.Price - tick, err := p.GetTicker() + tick, err := po.GetTicker() if err != nil { return tickerPrice, err } - for _, x := range p.GetEnabledCurrencies() { + for _, x := range po.GetEnabledCurrencies() { var tp ticker.Price - curr := exchange.FormatExchangeCurrency(p.GetName(), x).String() + curr := exchange.FormatExchangeCurrency(po.GetName(), x).String() tp.Pair = x tp.Ask = tick[curr].LowestAsk tp.Bid = tick[curr].HighestBid @@ -63,39 +63,39 @@ func (p *Poloniex) UpdateTicker(currencyPair pair.CurrencyPair, assetType string tp.Last = tick[curr].Last tp.Low = tick[curr].Low24Hr tp.Volume = tick[curr].BaseVolume - ticker.ProcessTicker(p.GetName(), x, tp, assetType) + ticker.ProcessTicker(po.GetName(), x, tp, assetType) } - return ticker.GetTicker(p.Name, currencyPair, assetType) + return ticker.GetTicker(po.Name, currencyPair, assetType) } // GetTickerPrice returns the ticker for a currency pair -func (p *Poloniex) GetTickerPrice(currencyPair pair.CurrencyPair, assetType string) (ticker.Price, error) { - tickerNew, err := ticker.GetTicker(p.GetName(), currencyPair, assetType) +func (po *Poloniex) GetTickerPrice(currencyPair pair.CurrencyPair, assetType string) (ticker.Price, error) { + tickerNew, err := ticker.GetTicker(po.GetName(), currencyPair, assetType) if err != nil { - return p.UpdateTicker(currencyPair, assetType) + return po.UpdateTicker(currencyPair, assetType) } return tickerNew, nil } // GetOrderbookEx returns orderbook base on the currency pair -func (p *Poloniex) GetOrderbookEx(currencyPair pair.CurrencyPair, assetType string) (orderbook.Base, error) { - ob, err := orderbook.GetOrderbook(p.GetName(), currencyPair, assetType) +func (po *Poloniex) GetOrderbookEx(currencyPair pair.CurrencyPair, assetType string) (orderbook.Base, error) { + ob, err := orderbook.GetOrderbook(po.GetName(), currencyPair, assetType) if err != nil { - return p.UpdateOrderbook(currencyPair, assetType) + return po.UpdateOrderbook(currencyPair, assetType) } return ob, nil } // UpdateOrderbook updates and returns the orderbook for a currency pair -func (p *Poloniex) UpdateOrderbook(currencyPair pair.CurrencyPair, assetType string) (orderbook.Base, error) { +func (po *Poloniex) UpdateOrderbook(currencyPair pair.CurrencyPair, assetType string) (orderbook.Base, error) { var orderBook orderbook.Base - orderbookNew, err := p.GetOrderbook("", 1000) + orderbookNew, err := po.GetOrderbook("", 1000) if err != nil { return orderBook, err } - for _, x := range p.GetEnabledCurrencies() { - currency := exchange.FormatExchangeCurrency(p.Name, x).String() + for _, x := range po.GetEnabledCurrencies() { + currency := exchange.FormatExchangeCurrency(po.Name, x).String() data, ok := orderbookNew.Data[currency] if !ok { continue @@ -115,17 +115,17 @@ func (p *Poloniex) UpdateOrderbook(currencyPair pair.CurrencyPair, assetType str obItems = append(obItems, orderbook.Item{Amount: obData.Amount, Price: obData.Price}) } orderBook.Asks = obItems - orderbook.ProcessOrderbook(p.Name, x, orderBook, assetType) + orderbook.ProcessOrderbook(po.Name, x, orderBook, assetType) } - return orderbook.GetOrderbook(p.Name, currencyPair, assetType) + return orderbook.GetOrderbook(po.Name, currencyPair, assetType) } // GetExchangeAccountInfo retrieves balances for all enabled currencies for the // Poloniex exchange -func (p *Poloniex) GetExchangeAccountInfo() (exchange.AccountInfo, error) { +func (po *Poloniex) GetExchangeAccountInfo() (exchange.AccountInfo, error) { var response exchange.AccountInfo - response.ExchangeName = p.GetName() - accountBalance, err := p.GetBalances() + response.ExchangeName = po.GetName() + accountBalance, err := po.GetBalances() if err != nil { return response, err }