exchanges: Initial context propagation (#744)

* gct: phase one context awareness pass

* exchanges: context propagation pass

* common/requester: force context requirement

* gctcli/exchanges: linter fix

* rpcserver: fix test using dummy rpc server

* backtester: fix comments

* grpc: add correct cancel and timeout for commands

* rpcserver_test: add comment on dummy server

* common: deprecated SendHTTPGetRequest

* linter: fix

* linter: turn on no context check

* apichecker: fix context linter issue

* binance: use param context

* common: remove checks as this gets executed before main

* common: change mutex to RW as clients can be used by multiple go routines.

* common: remove init and JIT default client. Unexport global variables and add protection.

* common: Add comments

* bithumb: after dinner mints fix
This commit is contained in:
Ryan O'Hara-Reid
2021-09-11 13:52:07 +10:00
committed by GitHub
parent 72516f7268
commit d636049fb2
168 changed files with 8085 additions and 6996 deletions

View File

@@ -53,7 +53,7 @@ type HitBTC struct {
// GetCurrencies returns the actual list of available currencies, tokens, ICO
// etc.
func (h *HitBTC) GetCurrencies() (map[string]Currencies, error) {
func (h *HitBTC) GetCurrencies(ctx context.Context) (map[string]Currencies, error) {
type Response struct {
Data []Currencies
}
@@ -61,7 +61,7 @@ func (h *HitBTC) GetCurrencies() (map[string]Currencies, error) {
path := fmt.Sprintf("/%s", apiV2Currency)
ret := make(map[string]Currencies)
err := h.SendHTTPRequest(exchange.RestSpot, path, &resp.Data)
err := h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp.Data)
if err != nil {
return ret, err
}
@@ -74,14 +74,14 @@ func (h *HitBTC) GetCurrencies() (map[string]Currencies, error) {
// GetCurrency returns the actual list of available currencies, tokens, ICO
// etc.
func (h *HitBTC) GetCurrency(currency string) (Currencies, error) {
func (h *HitBTC) GetCurrency(ctx context.Context, currency string) (Currencies, error) {
type Response struct {
Data Currencies
}
resp := Response{}
path := fmt.Sprintf("/%s/%s", apiV2Currency, currency)
return resp.Data, h.SendHTTPRequest(exchange.RestSpot, path, &resp.Data)
return resp.Data, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp.Data)
}
// GetSymbols Return the actual list of currency symbols (currency pairs) traded
@@ -89,12 +89,12 @@ func (h *HitBTC) GetCurrency(currency string) (Currencies, error) {
// currency, and the second currency is called the quote currency. The currency
// pair indicates how much of the quote currency is needed to purchase one unit
// of the base currency.
func (h *HitBTC) GetSymbols(symbol string) ([]string, error) {
func (h *HitBTC) GetSymbols(ctx context.Context, symbol string) ([]string, error) {
var resp []Symbol
path := fmt.Sprintf("/%s/%s", apiV2Symbol, symbol)
ret := make([]string, 0, len(resp))
err := h.SendHTTPRequest(exchange.RestSpot, path, &resp)
err := h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
if err != nil {
return ret, err
}
@@ -107,28 +107,28 @@ func (h *HitBTC) GetSymbols(symbol string) ([]string, error) {
// GetSymbolsDetailed is the same as above but returns an array of symbols with
// all their details.
func (h *HitBTC) GetSymbolsDetailed() ([]Symbol, error) {
func (h *HitBTC) GetSymbolsDetailed(ctx context.Context) ([]Symbol, error) {
var resp []Symbol
path := fmt.Sprintf("/%s", apiV2Symbol)
return resp, h.SendHTTPRequest(exchange.RestSpot, path, &resp)
return resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
}
// GetTicker returns ticker information
func (h *HitBTC) GetTicker(symbol string) (TickerResponse, error) {
func (h *HitBTC) GetTicker(ctx context.Context, symbol string) (TickerResponse, error) {
var resp TickerResponse
path := fmt.Sprintf("/%s/%s", apiV2Ticker, symbol)
return resp, h.SendHTTPRequest(exchange.RestSpot, path, &resp)
return resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
}
// GetTickers returns ticker information
func (h *HitBTC) GetTickers() ([]TickerResponse, error) {
func (h *HitBTC) GetTickers(ctx context.Context) ([]TickerResponse, error) {
var resp []TickerResponse
path := fmt.Sprintf("/%s/", apiV2Ticker)
return resp, h.SendHTTPRequest(exchange.RestSpot, path, &resp)
return resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
}
// GetTrades returns trades from hitbtc
func (h *HitBTC) GetTrades(currencyPair, by, sort string, from, till, limit, offset int64) ([]TradeHistory, error) {
func (h *HitBTC) GetTrades(ctx context.Context, currencyPair, by, sort string, from, till, limit, offset int64) ([]TradeHistory, error) {
urlValues := url.Values{}
if from > 0 {
urlValues.Set("from", strconv.FormatInt(from, 10))
@@ -154,12 +154,12 @@ func (h *HitBTC) GetTrades(currencyPair, by, sort string, from, till, limit, off
apiV2Trades,
currencyPair,
urlValues.Encode())
return resp, h.SendHTTPRequest(exchange.RestSpot, path, &resp)
return resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
}
// GetOrderbook an order book is an electronic list of buy and sell orders for a
// specific symbol, organized by price level.
func (h *HitBTC) GetOrderbook(currencyPair string, limit int) (Orderbook, error) {
func (h *HitBTC) GetOrderbook(ctx context.Context, currencyPair string, limit int) (Orderbook, error) {
// limit Limit of orderbook levels, default 100. Set 0 to view full orderbook levels
vals := url.Values{}
@@ -173,7 +173,7 @@ func (h *HitBTC) GetOrderbook(currencyPair string, limit int) (Orderbook, error)
currencyPair,
vals.Encode())
err := h.SendHTTPRequest(exchange.RestSpot, path, &resp)
err := h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
if err != nil {
return Orderbook{}, err
}
@@ -186,7 +186,7 @@ func (h *HitBTC) GetOrderbook(currencyPair string, limit int) (Orderbook, error)
// GetCandles returns candles which is used for OHLC a specific currency.
// Note: Result contain candles only with non zero volume.
func (h *HitBTC) GetCandles(currencyPair, limit, period string, start, end time.Time) ([]ChartData, error) {
func (h *HitBTC) GetCandles(ctx context.Context, currencyPair, limit, period string, start, end time.Time) ([]ChartData, error) {
// limit Limit of candles, default 100.
// period One of: M1 (one minute), M3, M5, M15, M30, H1, H4, D1, D7, 1M (one month). Default is M30 (30 minutes).
vals := url.Values{}
@@ -212,16 +212,18 @@ func (h *HitBTC) GetCandles(currencyPair, limit, period string, start, end time.
var resp []ChartData
path := fmt.Sprintf("/%s/%s?%s", apiV2Candles, currencyPair, vals.Encode())
return resp, h.SendHTTPRequest(exchange.RestSpot, path, &resp)
return resp, h.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)
}
// Authenticated Market Data
// https://api.hitbtc.com/?python#market-data
// GetBalances returns full balance for your account
func (h *HitBTC) GetBalances() (map[string]Balance, error) {
func (h *HitBTC) GetBalances(ctx context.Context) (map[string]Balance, error) {
var result []Balance
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodGet,
err := h.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodGet,
apiV2Balance,
url.Values{},
otherRequests,
@@ -240,11 +242,11 @@ func (h *HitBTC) GetBalances() (map[string]Balance, error) {
}
// GetDepositAddresses returns a deposit address for a specific currency
func (h *HitBTC) GetDepositAddresses(currency string) (DepositCryptoAddresses, error) {
func (h *HitBTC) GetDepositAddresses(ctx context.Context, currency string) (DepositCryptoAddresses, error) {
var resp DepositCryptoAddresses
return resp,
h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodGet,
h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet,
apiV2CryptoAddress+"/"+currency,
url.Values{},
otherRequests,
@@ -252,9 +254,9 @@ func (h *HitBTC) GetDepositAddresses(currency string) (DepositCryptoAddresses, e
}
// GenerateNewAddress generates a new deposit address for a currency
func (h *HitBTC) GenerateNewAddress(currency string) (DepositCryptoAddresses, error) {
func (h *HitBTC) GenerateNewAddress(ctx context.Context, currency string) (DepositCryptoAddresses, error) {
resp := DepositCryptoAddresses{}
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
apiV2CryptoAddress+"/"+currency,
url.Values{},
otherRequests,
@@ -264,9 +266,9 @@ func (h *HitBTC) GenerateNewAddress(currency string) (DepositCryptoAddresses, er
}
// GetActiveorders returns all your active orders
func (h *HitBTC) GetActiveorders(currency string) ([]Order, error) {
func (h *HitBTC) GetActiveorders(ctx context.Context, currency string) ([]Order, error) {
var resp []Order
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodGet,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet,
orders+"?symbol="+currency,
url.Values{},
tradingRequests,
@@ -276,7 +278,7 @@ func (h *HitBTC) GetActiveorders(currency string) ([]Order, error) {
}
// GetTradeHistoryForCurrency returns your trade history
func (h *HitBTC) GetTradeHistoryForCurrency(currency, start, end string) (AuthenticatedTradeHistoryResponse, error) {
func (h *HitBTC) GetTradeHistoryForCurrency(ctx context.Context, currency, start, end string) (AuthenticatedTradeHistoryResponse, error) {
values := url.Values{}
if start != "" {
@@ -290,7 +292,7 @@ func (h *HitBTC) GetTradeHistoryForCurrency(currency, start, end string) (Authen
values.Set("currencyPair", currency)
result := AuthenticatedTradeHistoryResponse{}
return result, h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
return result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
apiV2TradeHistory,
values,
otherRequests,
@@ -298,7 +300,7 @@ func (h *HitBTC) GetTradeHistoryForCurrency(currency, start, end string) (Authen
}
// GetTradeHistoryForAllCurrencies returns your trade history
func (h *HitBTC) GetTradeHistoryForAllCurrencies(start, end string) (AuthenticatedTradeHistoryAll, error) {
func (h *HitBTC) GetTradeHistoryForAllCurrencies(ctx context.Context, start, end string) (AuthenticatedTradeHistoryAll, error) {
values := url.Values{}
if start != "" {
@@ -312,7 +314,7 @@ func (h *HitBTC) GetTradeHistoryForAllCurrencies(start, end string) (Authenticat
values.Set("currencyPair", "all")
result := AuthenticatedTradeHistoryAll{}
return result, h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
return result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
apiV2TradeHistory,
values,
otherRequests,
@@ -320,12 +322,12 @@ func (h *HitBTC) GetTradeHistoryForAllCurrencies(start, end string) (Authenticat
}
// GetOrders List of your order history.
func (h *HitBTC) GetOrders(currency string) ([]OrderHistoryResponse, error) {
func (h *HitBTC) GetOrders(ctx context.Context, currency string) ([]OrderHistoryResponse, error) {
values := url.Values{}
values.Set("symbol", currency)
var result []OrderHistoryResponse
return result, h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodGet,
return result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet,
apiV2OrderHistory,
values,
tradingRequests,
@@ -333,12 +335,12 @@ func (h *HitBTC) GetOrders(currency string) ([]OrderHistoryResponse, error) {
}
// GetOpenOrders List of your currently open orders.
func (h *HitBTC) GetOpenOrders(currency string) ([]OrderHistoryResponse, error) {
func (h *HitBTC) GetOpenOrders(ctx context.Context, currency string) ([]OrderHistoryResponse, error) {
values := url.Values{}
values.Set("symbol", currency)
var result []OrderHistoryResponse
return result, h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodGet,
return result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet,
apiv2OpenOrders,
values,
tradingRequests,
@@ -346,7 +348,7 @@ func (h *HitBTC) GetOpenOrders(currency string) ([]OrderHistoryResponse, error)
}
// PlaceOrder places an order on the exchange
func (h *HitBTC) PlaceOrder(currency string, rate, amount float64, orderType, side string) (OrderResponse, error) {
func (h *HitBTC) PlaceOrder(ctx context.Context, currency string, rate, amount float64, orderType, side string) (OrderResponse, error) {
var result OrderResponse
values := url.Values{}
@@ -357,7 +359,7 @@ func (h *HitBTC) PlaceOrder(currency string, rate, amount float64, orderType, si
values.Set("price", strconv.FormatFloat(rate, 'f', -1, 64))
values.Set("type", orderType)
return result, h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
return result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
apiOrder,
values,
tradingRequests,
@@ -365,11 +367,11 @@ func (h *HitBTC) PlaceOrder(currency string, rate, amount float64, orderType, si
}
// CancelExistingOrder cancels a specific order by OrderID
func (h *HitBTC) CancelExistingOrder(orderID int64) (bool, error) {
func (h *HitBTC) CancelExistingOrder(ctx context.Context, orderID int64) (bool, error) {
result := GenericResponse{}
values := url.Values{}
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodDelete,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete,
apiOrder+"/"+strconv.FormatInt(orderID, 10),
values,
tradingRequests,
@@ -387,10 +389,10 @@ func (h *HitBTC) CancelExistingOrder(orderID int64) (bool, error) {
}
// CancelAllExistingOrders cancels all open orders
func (h *HitBTC) CancelAllExistingOrders() ([]Order, error) {
func (h *HitBTC) CancelAllExistingOrders(ctx context.Context) ([]Order, error) {
var result []Order
values := url.Values{}
return result, h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodDelete,
return result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodDelete,
apiOrder,
values,
tradingRequests,
@@ -398,7 +400,7 @@ func (h *HitBTC) CancelAllExistingOrders() ([]Order, error) {
}
// MoveOrder generates a new move order
func (h *HitBTC) MoveOrder(orderID int64, rate, amount float64) (MoveOrderResponse, error) {
func (h *HitBTC) MoveOrder(ctx context.Context, orderID int64, rate, amount float64) (MoveOrderResponse, error) {
result := MoveOrderResponse{}
values := url.Values{}
values.Set("orderNumber", strconv.FormatInt(orderID, 10))
@@ -408,7 +410,7 @@ func (h *HitBTC) MoveOrder(orderID int64, rate, amount float64) (MoveOrderRespon
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
}
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
orderMove,
values,
tradingRequests,
@@ -426,7 +428,7 @@ func (h *HitBTC) MoveOrder(orderID int64, rate, amount float64) (MoveOrderRespon
}
// Withdraw allows for the withdrawal to a specific address
func (h *HitBTC) Withdraw(currency, address string, amount float64) (bool, error) {
func (h *HitBTC) Withdraw(ctx context.Context, currency, address string, amount float64) (bool, error) {
result := Withdraw{}
values := url.Values{}
@@ -434,7 +436,7 @@ func (h *HitBTC) Withdraw(currency, address string, amount float64) (bool, error
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
values.Set("address", address)
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
apiV2CryptoWithdraw,
values,
otherRequests,
@@ -452,9 +454,9 @@ func (h *HitBTC) Withdraw(currency, address string, amount float64) (bool, error
}
// GetFeeInfo returns current fee information
func (h *HitBTC) GetFeeInfo(currencyPair string) (Fee, error) {
func (h *HitBTC) GetFeeInfo(ctx context.Context, currencyPair string) (Fee, error) {
result := Fee{}
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodGet,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet,
apiV2FeeInfo+"/"+currencyPair,
url.Values{},
tradingRequests,
@@ -464,13 +466,13 @@ func (h *HitBTC) GetFeeInfo(currencyPair string) (Fee, error) {
}
// GetTradableBalances returns current tradable balances
func (h *HitBTC) GetTradableBalances() (map[string]map[string]float64, error) {
func (h *HitBTC) GetTradableBalances(ctx context.Context) (map[string]map[string]float64, error) {
type Response struct {
Data map[string]map[string]interface{}
}
result := Response{}
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
tradableBalances,
url.Values{},
tradingRequests,
@@ -493,7 +495,7 @@ func (h *HitBTC) GetTradableBalances() (map[string]map[string]float64, error) {
}
// TransferBalance transfers a balance
func (h *HitBTC) TransferBalance(currency, from, to string, amount float64) (bool, error) {
func (h *HitBTC) TransferBalance(ctx context.Context, currency, from, to string, amount float64) (bool, error) {
values := url.Values{}
result := GenericResponse{}
@@ -502,7 +504,7 @@ func (h *HitBTC) TransferBalance(currency, from, to string, amount float64) (boo
values.Set("fromAccount", from)
values.Set("toAccount", to)
err := h.SendAuthenticatedHTTPRequest(exchange.RestSpot, http.MethodPost,
err := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost,
transferBalance,
values,
otherRequests,
@@ -520,7 +522,7 @@ func (h *HitBTC) TransferBalance(currency, from, to string, amount float64) (boo
}
// SendHTTPRequest sends an unauthenticated HTTP request
func (h *HitBTC) SendHTTPRequest(ep exchange.URL, path string, result interface{}) error {
func (h *HitBTC) SendHTTPRequest(ctx context.Context, ep exchange.URL, path string, result interface{}) error {
endpoint, err := h.API.Endpoints.GetURL(ep)
if err != nil {
return err
@@ -535,13 +537,13 @@ func (h *HitBTC) SendHTTPRequest(ep exchange.URL, path string, result interface{
HTTPRecording: h.HTTPRecording,
}
return h.SendPayload(context.Background(), marketRequests, func() (*request.Item, error) {
return h.SendPayload(ctx, marketRequests, func() (*request.Item, error) {
return item, nil
})
}
// SendAuthenticatedHTTPRequest sends an authenticated http request
func (h *HitBTC) SendAuthenticatedHTTPRequest(ep exchange.URL, method, endpoint string, values url.Values, f request.EndpointLimit, result interface{}) error {
func (h *HitBTC) SendAuthenticatedHTTPRequest(ctx context.Context, ep exchange.URL, method, endpoint string, values url.Values, f request.EndpointLimit, result interface{}) error {
if !h.AllowAuthenticatedRequest() {
return fmt.Errorf("%s %w", h.Name, exchange.ErrAuthenticatedRequestWithoutCredentialsSet)
}
@@ -565,20 +567,21 @@ func (h *HitBTC) SendAuthenticatedHTTPRequest(ep exchange.URL, method, endpoint
HTTPRecording: h.HTTPRecording,
}
return h.SendPayload(context.Background(), f, func() (*request.Item, error) {
return h.SendPayload(ctx, f, func() (*request.Item, error) {
item.Body = bytes.NewBufferString(values.Encode())
return item, nil
})
}
// GetFee returns an estimate of fee based on type of transaction
func (h *HitBTC) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
func (h *HitBTC) GetFee(ctx context.Context, feeBuilder *exchange.FeeBuilder) (float64, error) {
var fee float64
switch feeBuilder.FeeType {
case exchange.CryptocurrencyTradeFee:
feeInfo, err := h.GetFeeInfo(feeBuilder.Pair.Base.String() +
feeBuilder.Pair.Delimiter +
feeBuilder.Pair.Quote.String())
feeInfo, err := h.GetFeeInfo(ctx,
feeBuilder.Pair.Base.String()+
feeBuilder.Pair.Delimiter+
feeBuilder.Pair.Quote.String())
if err != nil {
return 0, err
@@ -587,7 +590,7 @@ func (h *HitBTC) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
feeBuilder.Amount,
feeBuilder.IsMaker)
case exchange.CryptocurrencyWithdrawalFee:
currencyInfo, err := h.GetCurrency(feeBuilder.Pair.Base.String())
currencyInfo, err := h.GetCurrency(ctx, feeBuilder.Pair.Base.String())
if err != nil {
return 0, err
}

View File

@@ -1,6 +1,7 @@
package hitbtc
import (
"context"
"log"
"net/http"
"os"
@@ -55,21 +56,22 @@ func TestMain(m *testing.M) {
}
func TestGetOrderbook(t *testing.T) {
_, err := h.GetOrderbook("BTCUSD", 50)
_, err := h.GetOrderbook(context.Background(), "BTCUSD", 50)
if err != nil {
t.Error("Test faild - HitBTC GetOrderbook() error", err)
}
}
func TestGetTrades(t *testing.T) {
_, err := h.GetTrades("BTCUSD", "", "", 0, 0, 0, 0)
_, err := h.GetTrades(context.Background(), "BTCUSD", "", "", 0, 0, 0, 0)
if err != nil {
t.Error("Test faild - HitBTC GetTradeHistory() error", err)
}
}
func TestGetChartCandles(t *testing.T) {
_, err := h.GetCandles("BTCUSD", "", "D1", time.Now().Add(-24*time.Hour), time.Now())
_, err := h.GetCandles(context.Background(),
"BTCUSD", "", "D1", time.Now().Add(-24*time.Hour), time.Now())
if err != nil {
t.Error("Test faild - HitBTC GetChartData() error", err)
}
@@ -82,12 +84,14 @@ func TestGetHistoricCandles(t *testing.T) {
}
startTime := time.Now().Add(-time.Hour * 24)
end := time.Now()
_, err = h.GetHistoricCandles(currencyPair, asset.Spot, startTime, end, kline.OneMin)
_, err = h.GetHistoricCandles(context.Background(),
currencyPair, asset.Spot, startTime, end, kline.OneMin)
if err != nil {
t.Fatal(err)
}
_, err = h.GetHistoricCandles(currencyPair, asset.Spot, startTime, end, kline.Interval(time.Hour*7))
_, err = h.GetHistoricCandles(context.Background(),
currencyPair, asset.Spot, startTime, end, kline.Interval(time.Hour*7))
if err == nil {
t.Fatal("unexpected result")
}
@@ -100,19 +104,21 @@ func TestGetHistoricCandlesExtended(t *testing.T) {
}
startTime := time.Unix(1546300800, 0)
end := time.Unix(1577836799, 0)
_, err = h.GetHistoricCandlesExtended(currencyPair, asset.Spot, startTime, end, kline.OneHour)
_, err = h.GetHistoricCandlesExtended(context.Background(),
currencyPair, asset.Spot, startTime, end, kline.OneHour)
if err != nil {
t.Fatal(err)
}
_, err = h.GetHistoricCandlesExtended(currencyPair, asset.Spot, startTime, end, kline.Interval(time.Hour*7))
_, err = h.GetHistoricCandlesExtended(context.Background(),
currencyPair, asset.Spot, startTime, end, kline.Interval(time.Hour*7))
if err == nil {
t.Fatal("unexpected result")
}
}
func TestGetCurrencies(t *testing.T) {
_, err := h.GetCurrencies()
_, err := h.GetCurrencies(context.Background())
if err != nil {
t.Error("Test faild - HitBTC GetCurrencies() error", err)
}
@@ -132,7 +138,7 @@ func setFeeBuilder() *exchange.FeeBuilder {
// TestGetFeeByTypeOfflineTradeFee logic test
func TestGetFeeByTypeOfflineTradeFee(t *testing.T) {
var feeBuilder = setFeeBuilder()
_, err := h.GetFeeByType(feeBuilder)
_, err := h.GetFeeByType(context.Background(), feeBuilder)
if err != nil {
t.Fatal(err)
}
@@ -153,33 +159,36 @@ func TestUpdateTicker(t *testing.T) {
t.Fatal(err)
}
h.CurrencyPairs.StorePairs(asset.Spot, pairs, true)
_, err = h.UpdateTicker(currency.NewPair(currency.BTC, currency.USD), asset.Spot)
_, err = h.UpdateTicker(context.Background(),
currency.NewPair(currency.BTC, currency.USD),
asset.Spot)
if err != nil {
t.Error(err)
}
_, err = h.FetchTicker(currency.NewPair(currency.XRP, currency.USD), asset.Spot)
_, err = h.FetchTicker(context.Background(),
currency.NewPair(currency.XRP, currency.USD), asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestUpdateTickers(t *testing.T) {
err := h.UpdateTickers(asset.Spot)
err := h.UpdateTickers(context.Background(), asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestGetAllTickers(t *testing.T) {
_, err := h.GetTickers()
_, err := h.GetTickers(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetSingularTicker(t *testing.T) {
_, err := h.GetTicker("BTCUSD")
_, err := h.GetTicker(context.Background(), "BTCUSD")
if err != nil {
t.Error(err)
}
@@ -189,7 +198,7 @@ func TestGetFee(t *testing.T) {
var feeBuilder = setFeeBuilder()
if areTestAPIKeysSet() {
// CryptocurrencyTradeFee Basic
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
@@ -197,32 +206,32 @@ func TestGetFee(t *testing.T) {
feeBuilder = setFeeBuilder()
feeBuilder.Amount = 1000
feeBuilder.PurchasePrice = 1000
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
// CryptocurrencyTradeFee IsMaker
feeBuilder = setFeeBuilder()
feeBuilder.IsMaker = true
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
// CryptocurrencyTradeFee Negative purchase price
feeBuilder = setFeeBuilder()
feeBuilder.PurchasePrice = -1000
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
// CryptocurrencyWithdrawalFee Basic
feeBuilder = setFeeBuilder()
feeBuilder.FeeType = exchange.CryptocurrencyWithdrawalFee
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
// CryptocurrencyWithdrawalFee Invalid currency
feeBuilder = setFeeBuilder()
feeBuilder.Pair.Base = currency.NewCode("hello")
feeBuilder.FeeType = exchange.CryptocurrencyWithdrawalFee
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
}
@@ -232,14 +241,14 @@ func TestGetFee(t *testing.T) {
feeBuilder.FeeType = exchange.CryptocurrencyDepositFee
feeBuilder.Pair.Base = currency.BTC
feeBuilder.Pair.Quote = currency.LTC
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
// InternationalBankDepositFee Basic
feeBuilder = setFeeBuilder()
feeBuilder.FeeType = exchange.InternationalBankDepositFee
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
@@ -247,7 +256,7 @@ func TestGetFee(t *testing.T) {
feeBuilder = setFeeBuilder()
feeBuilder.FeeType = exchange.InternationalBankWithdrawalFee
feeBuilder.FiatCurrency = currency.USD
if _, err := h.GetFee(feeBuilder); err != nil {
if _, err := h.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
}
@@ -267,7 +276,7 @@ func TestGetActiveOrders(t *testing.T) {
AssetType: asset.Spot,
}
_, err := h.GetActiveOrders(&getOrdersRequest)
_, err := h.GetActiveOrders(context.Background(), &getOrdersRequest)
if areTestAPIKeysSet() && err != nil {
t.Errorf("Could not get open orders: %s", err)
} else if !areTestAPIKeysSet() && err == nil {
@@ -282,7 +291,7 @@ func TestGetOrderHistory(t *testing.T) {
Pairs: []currency.Pair{currency.NewPair(currency.ETH, currency.BTC)},
}
_, err := h.GetOrderHistory(&getOrdersRequest)
_, err := h.GetOrderHistory(context.Background(), &getOrdersRequest)
if areTestAPIKeysSet() && err != nil {
t.Errorf("Could not get order history: %s", err)
} else if !areTestAPIKeysSet() && err == nil {
@@ -313,7 +322,7 @@ func TestSubmitOrder(t *testing.T) {
ClientID: "meowOrder",
AssetType: asset.Spot,
}
response, err := h.SubmitOrder(orderSubmission)
response, err := h.SubmitOrder(context.Background(), orderSubmission)
if areTestAPIKeysSet() && (err != nil || !response.IsOrderPlaced) {
t.Errorf("Order failed to be placed: %v", err)
} else if !areTestAPIKeysSet() && err == nil {
@@ -335,7 +344,7 @@ func TestCancelExchangeOrder(t *testing.T) {
AssetType: asset.Spot,
}
err := h.CancelOrder(orderCancellation)
err := h.CancelOrder(context.Background(), orderCancellation)
if !areTestAPIKeysSet() && err == nil {
t.Error("Expecting an error when no keys are set")
}
@@ -358,7 +367,7 @@ func TestCancelAllExchangeOrders(t *testing.T) {
AssetType: asset.Spot,
}
resp, err := h.CancelAllOrders(orderCancellation)
resp, err := h.CancelAllOrders(context.Background(), orderCancellation)
if !areTestAPIKeysSet() && err == nil {
t.Error("Expecting an error when no keys are set")
@@ -376,7 +385,8 @@ func TestModifyOrder(t *testing.T) {
if areTestAPIKeysSet() && !canManipulateRealOrders {
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
}
_, err := h.ModifyOrder(&order.Modify{AssetType: asset.Spot})
_, err := h.ModifyOrder(context.Background(),
&order.Modify{AssetType: asset.Spot})
if err == nil {
t.Error("ModifyOrder() Expected error")
}
@@ -396,7 +406,8 @@ func TestWithdraw(t *testing.T) {
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
}
_, err := h.WithdrawCryptocurrencyFunds(&withdrawCryptoRequest)
_, err := h.WithdrawCryptocurrencyFunds(context.Background(),
&withdrawCryptoRequest)
if !areTestAPIKeysSet() && err == nil {
t.Error("Expecting an error when no keys are set")
}
@@ -411,7 +422,7 @@ func TestWithdrawFiat(t *testing.T) {
}
var withdrawFiatRequest = withdraw.Request{}
_, err := h.WithdrawFiatFunds(&withdrawFiatRequest)
_, err := h.WithdrawFiatFunds(context.Background(), &withdrawFiatRequest)
if err != common.ErrFunctionNotSupported {
t.Errorf("Expected '%v', received: '%v'", common.ErrFunctionNotSupported, err)
}
@@ -423,7 +434,8 @@ func TestWithdrawInternationalBank(t *testing.T) {
}
var withdrawFiatRequest = withdraw.Request{}
_, err := h.WithdrawFiatFundsToInternationalBank(&withdrawFiatRequest)
_, err := h.WithdrawFiatFundsToInternationalBank(context.Background(),
&withdrawFiatRequest)
if err != common.ErrFunctionNotSupported {
t.Errorf("Expected '%v', received: '%v'", common.ErrFunctionNotSupported, err)
}
@@ -431,12 +443,12 @@ func TestWithdrawInternationalBank(t *testing.T) {
func TestGetDepositAddress(t *testing.T) {
if areTestAPIKeysSet() {
_, err := h.GetDepositAddress(currency.BTC, "")
_, err := h.GetDepositAddress(context.Background(), currency.BTC, "")
if err != nil {
t.Error("GetDepositAddress() error", err)
}
} else {
_, err := h.GetDepositAddress(currency.BTC, "")
_, err := h.GetDepositAddress(context.Background(), currency.BTC, "")
if err == nil {
t.Error("GetDepositAddress() error cannot be nil")
}
@@ -1001,7 +1013,7 @@ func TestGetRecentTrades(t *testing.T) {
if err != nil {
t.Fatal(err)
}
_, err = h.GetRecentTrades(currencyPair, asset.Spot)
_, err = h.GetRecentTrades(context.Background(), currencyPair, asset.Spot)
if err != nil {
t.Error(err)
}
@@ -1013,12 +1025,16 @@ func TestGetHistoricTrades(t *testing.T) {
if err != nil {
t.Fatal(err)
}
_, err = h.GetHistoricTrades(currencyPair, asset.Spot, time.Now().Add(-time.Minute*15), time.Now())
_, err = h.GetHistoricTrades(context.Background(),
currencyPair, asset.Spot, time.Now().Add(-time.Minute*15), time.Now())
if err != nil && err != common.ErrFunctionNotSupported {
t.Error(err)
}
// longer term
_, err = h.GetHistoricTrades(currencyPair, asset.Spot, time.Now().Add(-time.Minute*60*200), time.Now().Add(-time.Minute*60*199))
_, err = h.GetHistoricTrades(context.Background(),
currencyPair, asset.Spot,
time.Now().Add(-time.Minute*60*200),
time.Now().Add(-time.Minute*60*199))
if err != nil {
t.Error(err)
}

View File

@@ -1,6 +1,7 @@
package hitbtc
import (
"context"
"errors"
"fmt"
"sort"
@@ -41,7 +42,7 @@ func (h *HitBTC) GetDefaultConfig() (*config.ExchangeConfig, error) {
}
if h.Features.Supports.RESTCapabilities.AutoPairUpdates {
err = h.UpdateTradablePairs(true)
err = h.UpdateTradablePairs(context.TODO(), true)
if err != nil {
return nil, err
}
@@ -260,7 +261,7 @@ func (h *HitBTC) Run() {
return
}
err = h.UpdateTradablePairs(forceUpdate)
err = h.UpdateTradablePairs(context.TODO(), forceUpdate)
if err != nil {
log.Errorf(log.ExchangeSys,
"%s failed to update tradable pairs. Err: %s",
@@ -270,8 +271,8 @@ func (h *HitBTC) Run() {
}
// FetchTradablePairs returns a list of the exchanges tradable pairs
func (h *HitBTC) FetchTradablePairs(asset asset.Item) ([]string, error) {
symbols, err := h.GetSymbolsDetailed()
func (h *HitBTC) FetchTradablePairs(ctx context.Context, asset asset.Item) ([]string, error) {
symbols, err := h.GetSymbolsDetailed(ctx)
if err != nil {
return nil, err
}
@@ -292,8 +293,8 @@ func (h *HitBTC) FetchTradablePairs(asset asset.Item) ([]string, error) {
// UpdateTradablePairs updates the exchanges available pairs and stores
// them in the exchanges config
func (h *HitBTC) UpdateTradablePairs(forceUpdate bool) error {
pairs, err := h.FetchTradablePairs(asset.Spot)
func (h *HitBTC) UpdateTradablePairs(ctx context.Context, forceUpdate bool) error {
pairs, err := h.FetchTradablePairs(ctx, asset.Spot)
if err != nil {
return err
}
@@ -306,8 +307,8 @@ func (h *HitBTC) UpdateTradablePairs(forceUpdate bool) error {
}
// UpdateTickers updates the ticker for all currency pairs of a given asset type
func (h *HitBTC) UpdateTickers(a asset.Item) error {
tick, err := h.GetTickers()
func (h *HitBTC) UpdateTickers(ctx context.Context, a asset.Item) error {
tick, err := h.GetTickers(ctx)
if err != nil {
return err
}
@@ -356,8 +357,8 @@ func (h *HitBTC) UpdateTickers(a asset.Item) error {
}
// UpdateTicker updates and returns the ticker for a currency pair
func (h *HitBTC) UpdateTicker(p currency.Pair, a asset.Item) (*ticker.Price, error) {
err := h.UpdateTickers(a)
func (h *HitBTC) UpdateTicker(ctx context.Context, p currency.Pair, a asset.Item) (*ticker.Price, error) {
err := h.UpdateTickers(ctx, a)
if err != nil {
return nil, err
}
@@ -365,25 +366,25 @@ func (h *HitBTC) UpdateTicker(p currency.Pair, a asset.Item) (*ticker.Price, err
}
// FetchTicker returns the ticker for a currency pair
func (h *HitBTC) FetchTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error) {
func (h *HitBTC) FetchTicker(ctx context.Context, p currency.Pair, assetType asset.Item) (*ticker.Price, error) {
tickerNew, err := ticker.GetTicker(h.Name, p, assetType)
if err != nil {
return h.UpdateTicker(p, assetType)
return h.UpdateTicker(ctx, p, assetType)
}
return tickerNew, nil
}
// FetchOrderbook returns orderbook base on the currency pair
func (h *HitBTC) FetchOrderbook(p currency.Pair, assetType asset.Item) (*orderbook.Base, error) {
func (h *HitBTC) FetchOrderbook(ctx context.Context, p currency.Pair, assetType asset.Item) (*orderbook.Base, error) {
ob, err := orderbook.Get(h.Name, p, assetType)
if err != nil {
return h.UpdateOrderbook(p, assetType)
return h.UpdateOrderbook(ctx, p, assetType)
}
return ob, nil
}
// UpdateOrderbook updates and returns the orderbook for a currency pair
func (h *HitBTC) UpdateOrderbook(c currency.Pair, assetType asset.Item) (*orderbook.Base, error) {
func (h *HitBTC) UpdateOrderbook(ctx context.Context, c currency.Pair, assetType asset.Item) (*orderbook.Base, error) {
book := &orderbook.Base{
Exchange: h.Name,
Pair: c,
@@ -395,7 +396,7 @@ func (h *HitBTC) UpdateOrderbook(c currency.Pair, assetType asset.Item) (*orderb
return book, err
}
orderbookNew, err := h.GetOrderbook(fpair.String(), 1000)
orderbookNew, err := h.GetOrderbook(ctx, fpair.String(), 1000)
if err != nil {
return book, err
}
@@ -422,10 +423,10 @@ func (h *HitBTC) UpdateOrderbook(c currency.Pair, assetType asset.Item) (*orderb
// UpdateAccountInfo retrieves balances for all enabled currencies for the
// HitBTC exchange
func (h *HitBTC) UpdateAccountInfo(assetType asset.Item) (account.Holdings, error) {
func (h *HitBTC) UpdateAccountInfo(ctx context.Context, assetType asset.Item) (account.Holdings, error) {
var response account.Holdings
response.Exchange = h.Name
accountBalance, err := h.GetBalances()
accountBalance, err := h.GetBalances(ctx)
if err != nil {
return response, err
}
@@ -452,10 +453,10 @@ func (h *HitBTC) UpdateAccountInfo(assetType asset.Item) (account.Holdings, erro
}
// FetchAccountInfo retrieves balances for all enabled currencies
func (h *HitBTC) FetchAccountInfo(assetType asset.Item) (account.Holdings, error) {
func (h *HitBTC) FetchAccountInfo(ctx context.Context, assetType asset.Item) (account.Holdings, error) {
acc, err := account.GetHoldings(h.Name, assetType)
if err != nil {
return h.UpdateAccountInfo(assetType)
return h.UpdateAccountInfo(ctx, assetType)
}
return acc, nil
@@ -463,22 +464,22 @@ func (h *HitBTC) FetchAccountInfo(assetType asset.Item) (account.Holdings, error
// GetFundingHistory returns funding history, deposits and
// withdrawals
func (h *HitBTC) GetFundingHistory() ([]exchange.FundHistory, error) {
func (h *HitBTC) GetFundingHistory(ctx context.Context) ([]exchange.FundHistory, error) {
return nil, common.ErrFunctionNotSupported
}
// GetWithdrawalsHistory returns previous withdrawals data
func (h *HitBTC) GetWithdrawalsHistory(c currency.Code) (resp []exchange.WithdrawalHistory, err error) {
func (h *HitBTC) GetWithdrawalsHistory(ctx context.Context, c currency.Code) (resp []exchange.WithdrawalHistory, err error) {
return nil, common.ErrNotYetImplemented
}
// GetRecentTrades returns the most recent trades for a currency and asset
func (h *HitBTC) GetRecentTrades(p currency.Pair, assetType asset.Item) ([]trade.Data, error) {
return h.GetHistoricTrades(p, assetType, time.Now().Add(-time.Minute*15), time.Now())
func (h *HitBTC) GetRecentTrades(ctx context.Context, p currency.Pair, assetType asset.Item) ([]trade.Data, error) {
return h.GetHistoricTrades(ctx, p, assetType, time.Now().Add(-time.Minute*15), time.Now())
}
// GetHistoricTrades returns historic trade data within the timeframe provided
func (h *HitBTC) GetHistoricTrades(p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]trade.Data, error) {
func (h *HitBTC) GetHistoricTrades(ctx context.Context, p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]trade.Data, error) {
if err := common.StartEndTimeCheck(timestampStart, timestampEnd); err != nil {
return nil, fmt.Errorf("invalid time range supplied. Start: %v End %v %w", timestampStart, timestampEnd, err)
}
@@ -493,7 +494,14 @@ func (h *HitBTC) GetHistoricTrades(p currency.Pair, assetType asset.Item, timest
allTrades:
for {
var tradeData []TradeHistory
tradeData, err = h.GetTrades(p.String(), "", "", ts.UnixNano()/int64(time.Millisecond), timestampEnd.UnixNano()/int64(time.Millisecond), int64(limit), 0)
tradeData, err = h.GetTrades(ctx,
p.String(),
"",
"",
ts.UnixNano()/int64(time.Millisecond),
timestampEnd.UnixNano()/int64(time.Millisecond),
int64(limit),
0)
if err != nil {
return nil, err
}
@@ -539,7 +547,7 @@ allTrades:
}
// SubmitOrder submits a new order
func (h *HitBTC) SubmitOrder(o *order.Submit) (order.SubmitResponse, error) {
func (h *HitBTC) SubmitOrder(ctx context.Context, o *order.Submit) (order.SubmitResponse, error) {
var submitOrderResponse order.SubmitResponse
err := o.Validate()
if err != nil {
@@ -562,7 +570,8 @@ func (h *HitBTC) SubmitOrder(o *order.Submit) (order.SubmitResponse, error) {
}
var response OrderResponse
response, err = h.PlaceOrder(fPair.String(),
response, err = h.PlaceOrder(ctx,
fPair.String(),
o.Price,
o.Amount,
strings.ToLower(o.Type.String()),
@@ -584,12 +593,12 @@ func (h *HitBTC) SubmitOrder(o *order.Submit) (order.SubmitResponse, error) {
// ModifyOrder will allow of changing orderbook placement and limit to
// market conversion
func (h *HitBTC) ModifyOrder(action *order.Modify) (order.Modify, error) {
func (h *HitBTC) ModifyOrder(ctx context.Context, action *order.Modify) (order.Modify, error) {
return order.Modify{}, common.ErrFunctionNotSupported
}
// CancelOrder cancels an order by its corresponding ID number
func (h *HitBTC) CancelOrder(o *order.Cancel) error {
func (h *HitBTC) CancelOrder(ctx context.Context, o *order.Cancel) error {
if err := o.Validate(o.StandardCancel()); err != nil {
return err
}
@@ -599,22 +608,22 @@ func (h *HitBTC) CancelOrder(o *order.Cancel) error {
return err
}
_, err = h.CancelExistingOrder(orderIDInt)
_, err = h.CancelExistingOrder(ctx, orderIDInt)
return err
}
// CancelBatchOrders cancels an orders by their corresponding ID numbers
func (h *HitBTC) CancelBatchOrders(o []order.Cancel) (order.CancelBatchResponse, error) {
func (h *HitBTC) CancelBatchOrders(ctx context.Context, o []order.Cancel) (order.CancelBatchResponse, error) {
return order.CancelBatchResponse{}, common.ErrNotYetImplemented
}
// CancelAllOrders cancels all orders associated with a currency pair
func (h *HitBTC) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, error) {
func (h *HitBTC) CancelAllOrders(ctx context.Context, _ *order.Cancel) (order.CancelAllResponse, error) {
cancelAllOrdersResponse := order.CancelAllResponse{
Status: make(map[string]string),
}
resp, err := h.CancelAllExistingOrders()
resp, err := h.CancelAllExistingOrders(ctx)
if err != nil {
return cancelAllOrdersResponse, err
}
@@ -632,14 +641,14 @@ func (h *HitBTC) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, erro
}
// GetOrderInfo returns order information based on order ID
func (h *HitBTC) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
func (h *HitBTC) GetOrderInfo(ctx context.Context, orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
var orderDetail order.Detail
return orderDetail, common.ErrNotYetImplemented
}
// GetDepositAddress returns a deposit address for a specified currency
func (h *HitBTC) GetDepositAddress(currency currency.Code, _ string) (string, error) {
resp, err := h.GetDepositAddresses(currency.String())
func (h *HitBTC) GetDepositAddress(ctx context.Context, c currency.Code, _ string) (string, error) {
resp, err := h.GetDepositAddresses(ctx, c.String())
if err != nil {
return "", err
}
@@ -649,11 +658,14 @@ func (h *HitBTC) GetDepositAddress(currency currency.Code, _ string) (string, er
// WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is
// submitted
func (h *HitBTC) WithdrawCryptocurrencyFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error) {
func (h *HitBTC) WithdrawCryptocurrencyFunds(ctx context.Context, withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error) {
if err := withdrawRequest.Validate(); err != nil {
return nil, err
}
v, err := h.Withdraw(withdrawRequest.Currency.String(), withdrawRequest.Crypto.Address, withdrawRequest.Amount)
v, err := h.Withdraw(ctx,
withdrawRequest.Currency.String(),
withdrawRequest.Crypto.Address,
withdrawRequest.Amount)
if err != nil {
return nil, err
}
@@ -664,27 +676,27 @@ func (h *HitBTC) WithdrawCryptocurrencyFunds(withdrawRequest *withdraw.Request)
// WithdrawFiatFunds returns a withdrawal ID when a
// withdrawal is submitted
func (h *HitBTC) WithdrawFiatFunds(_ *withdraw.Request) (*withdraw.ExchangeResponse, error) {
func (h *HitBTC) WithdrawFiatFunds(_ context.Context, _ *withdraw.Request) (*withdraw.ExchangeResponse, error) {
return nil, common.ErrFunctionNotSupported
}
// WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a
// withdrawal is submitted
func (h *HitBTC) WithdrawFiatFundsToInternationalBank(_ *withdraw.Request) (*withdraw.ExchangeResponse, error) {
func (h *HitBTC) WithdrawFiatFundsToInternationalBank(_ context.Context, _ *withdraw.Request) (*withdraw.ExchangeResponse, error) {
return nil, common.ErrFunctionNotSupported
}
// GetFeeByType returns an estimate of fee based on type of transaction
func (h *HitBTC) GetFeeByType(feeBuilder *exchange.FeeBuilder) (float64, error) {
func (h *HitBTC) GetFeeByType(ctx context.Context, feeBuilder *exchange.FeeBuilder) (float64, error) {
if !h.AllowAuthenticatedRequest() && // Todo check connection status
feeBuilder.FeeType == exchange.CryptocurrencyTradeFee {
feeBuilder.FeeType = exchange.OfflineTradeFee
}
return h.GetFee(feeBuilder)
return h.GetFee(ctx, feeBuilder)
}
// GetActiveOrders retrieves any orders that are active/open
func (h *HitBTC) GetActiveOrders(req *order.GetOrdersRequest) ([]order.Detail, error) {
func (h *HitBTC) GetActiveOrders(ctx context.Context, req *order.GetOrdersRequest) ([]order.Detail, error) {
if err := req.Validate(); err != nil {
return nil, err
}
@@ -695,7 +707,7 @@ func (h *HitBTC) GetActiveOrders(req *order.GetOrdersRequest) ([]order.Detail, e
var allOrders []OrderHistoryResponse
for i := range req.Pairs {
resp, err := h.GetOpenOrders(req.Pairs[i].String())
resp, err := h.GetOpenOrders(ctx, req.Pairs[i].String())
if err != nil {
return nil, err
}
@@ -734,7 +746,7 @@ func (h *HitBTC) GetActiveOrders(req *order.GetOrdersRequest) ([]order.Detail, e
// GetOrderHistory retrieves account order information
// Can Limit response to specific order status
func (h *HitBTC) GetOrderHistory(req *order.GetOrdersRequest) ([]order.Detail, error) {
func (h *HitBTC) GetOrderHistory(ctx context.Context, req *order.GetOrdersRequest) ([]order.Detail, error) {
if err := req.Validate(); err != nil {
return nil, err
}
@@ -745,7 +757,7 @@ func (h *HitBTC) GetOrderHistory(req *order.GetOrdersRequest) ([]order.Detail, e
var allOrders []OrderHistoryResponse
for i := range req.Pairs {
resp, err := h.GetOrders(req.Pairs[i].String())
resp, err := h.GetOrders(ctx, req.Pairs[i].String())
if err != nil {
return nil, err
}
@@ -783,14 +795,14 @@ func (h *HitBTC) GetOrderHistory(req *order.GetOrdersRequest) ([]order.Detail, e
}
// AuthenticateWebsocket sends an authentication message to the websocket
func (h *HitBTC) AuthenticateWebsocket() error {
func (h *HitBTC) AuthenticateWebsocket(_ context.Context) error {
return h.wsLogin()
}
// ValidateCredentials validates current credentials used for wrapper
// functionality
func (h *HitBTC) ValidateCredentials(assetType asset.Item) error {
_, err := h.UpdateAccountInfo(assetType)
func (h *HitBTC) ValidateCredentials(ctx context.Context, assetType asset.Item) error {
_, err := h.UpdateAccountInfo(ctx, assetType)
return h.CheckTransientError(err)
}
@@ -809,7 +821,7 @@ func (h *HitBTC) FormatExchangeKlineInterval(in kline.Interval) string {
}
// GetHistoricCandles returns candles between a time period for a set time interval
func (h *HitBTC) GetHistoricCandles(pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) {
func (h *HitBTC) GetHistoricCandles(ctx context.Context, pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) {
if err := h.ValidateKline(pair, a, interval); err != nil {
return kline.Item{}, err
}
@@ -819,10 +831,12 @@ func (h *HitBTC) GetHistoricCandles(pair currency.Pair, a asset.Item, start, end
return kline.Item{}, err
}
data, err := h.GetCandles(formattedPair.String(),
data, err := h.GetCandles(ctx,
formattedPair.String(),
strconv.FormatInt(int64(h.Features.Enabled.Kline.ResultLimit), 10),
h.FormatExchangeKlineInterval(interval),
start, end)
start,
end)
if err != nil {
return kline.Item{}, err
}
@@ -849,7 +863,7 @@ func (h *HitBTC) GetHistoricCandles(pair currency.Pair, a asset.Item, start, end
}
// GetHistoricCandlesExtended returns candles between a time period for a set time interval
func (h *HitBTC) GetHistoricCandlesExtended(pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) {
func (h *HitBTC) GetHistoricCandlesExtended(ctx context.Context, pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) {
if err := h.ValidateKline(pair, a, interval); err != nil {
return kline.Item{}, err
}
@@ -871,10 +885,12 @@ func (h *HitBTC) GetHistoricCandlesExtended(pair currency.Pair, a asset.Item, st
for y := range dates.Ranges {
var data []ChartData
data, err = h.GetCandles(formattedPair.String(),
data, err = h.GetCandles(ctx,
formattedPair.String(),
strconv.FormatInt(int64(h.Features.Enabled.Kline.ResultLimit), 10),
h.FormatExchangeKlineInterval(interval),
dates.Ranges[y].Start.Time, dates.Ranges[y].End.Time)
dates.Ranges[y].Start.Time,
dates.Ranges[y].End.Time)
if err != nil {
return kline.Item{}, err
}