Files
gocryptotrader/exchanges/hitbtc/hitbtc.go
Ryan O'Hara-Reid 14c72c9c6b Currency System Update (#448)
* initial update of currency system

* WIP progress

* Finish initial currency string error returns

* fix whoopsie testing for non https insecureinos

* Current WIP for getEnabledPairs check and error return

* WIP continued

* When getting enabled pairs throw error when item is not contained in available pairs list

* More updates -WIP

* Wip continued including potential interface

* Current WIP

* pairs manager pass

* drop asset string and just use the map key, plus return some errors and create more work for myself.

* clean and fixed a bug in currency.json, will not populate correctly without coinmarketcap api keys set.

* purge logger references after merge

* go mod tidy after merge

* Pointer change WIP

* fix some issues and added error returns to a few items (WIP)

* WIP

* Clean

* Fix some linter issues

* Fix more linter issues

* even more linters

* xtda nits

* revert pointer change and rm field

* Addr madcozbadd nits

* fix linter issues: shadow declarations

* Fix linter issues: gocritic huge things

* linter issue fix

* Addr nits

* flush go mod files

* after merge woops

* fix shadow dec

* Addr thrasher nits

* addr nits

* fix some issues

* more fixes

* RM println

* Addr glorious nits

* Add helper method for setting assets

* add missing format directive

* Addr nits

* Actually process new futures contracts -_- derp

* WIP for GRPC upgrade for pair management

* update config pairs

* finished disabling and enabling asset

* linked update of tradable pairs to cli

* fix oopsies

* defer writing to file on program termination for currency storage system

* update template

* don't add disabled asset items to initial sync

* Fix enable disabling a list of pairs and added in a slice error type so we can add whats allowable without throwing an error and return a report, also addressed some other nits

* WIP on getting a channel to unsub

* Wip track down unsubscribe bug and start creating streaming interface

* purge websocket orderbook object and centralised updating routine for orderbook

* general clean before interface implementation

* stage one connection interface WIP

* WIP

* repackage wshandler WIP

* find difference of subs and change signature of subscriber functions so we can batch subscriptions and unsubscription in exchanges that support it

* design change on mange subscription routine WIP

* integrated ZB with the new webosocket updates

* WIP - okex conversion

* integrate websocket upgrades for lakebtc, kraken, huobi, hitbtc, gateio, and WIP for coinbene

* integrate another range of exchanges for websocket update

* Added subscriber and unsubscriber methods to websocket functionality

* fixed tests WIP

* amalgamate cache setup with main websocket setup

* reinstate exported fields traffic alert and shutdownC to accommodate gemini and lakebtc implementations

* added in colon

* Updated websocket auth handling as they werent getting passed through. Added a setter method for websocket URL due to the Binance generated auth key/listenKey. Fixed bug which stopped reconnection.

* Fix subscribe candle bug
Fix time conversion in candle
Fix inititial candle history to datahandler
Include funding to orderbook handling
Include funding to trades
Reduce code duplication in sub and unsub functions
Added the ability to include funding currency websocket subscriptions
validated all channels and added more items todo list (Auth items)

* RM line

* bitstamp pass

* btcmarkets pass - still needs to implement unsubscriber functionality and pairs change test.

* Batch outgoing subscriptions and fix unsubscribe bug

* BTSE - bumped time to minute to reduce pinger calling by 75 calls per day. Fix authentication bug and add authentication pass into to-do. Batch outgoing subscription calls

* fix type field and batch outgoing subs and unsubs for coinbasepro

* Batch outgoing subs and unsubs

* Fixes bug when matching return from authentication

* Fix bug where params where being sent out of order due to map ,where depth items werent being subscribed too, where trying to subscribe to too many kline items caused error, where trying to get a nano secocond ID conflicted due to speed of generation.

* Add websocket capability for currency pair change by utilizing full channel subscription list in subscribe function.

* Add error handling

* Fix public: time conversions, subscription list, stopped pushing heartbeat to data handler, aggregated list of connections.

* hitBTC pass

* returned nil instead of error due to period null bids and asks updates coming through.

* Fix auth ping capture and reply. Added in interval handling for kline data. Added correct full trade data handling. Fix subscribe and unsubscribe.

* Fix when websocket auth conn and token generation fail we don't try and auth sub. Fix bug between auth and normal connection id generation and matching. Batch outgoing payloads to increase efficiency. Updated matching functions to utilise channels instead of waitgroups and go routines.

* RM debug output

* rm func to get shutdown channel

* Add unsubscriber functionality, added wsTicker type, removed return as this will impede data flow and cause reconnection when handling and processing data

* okgroup WIP

* *Added missing fields for websocket trades
*Fix bug processing kline interval
*Added fields for websocket ticker struct
*Fix auth bug
	-Updated request and response matching param to interface so we can custom signature match. Stops auth subscribing before a reply is issued.
	-Updated channel inclusion of pair fo auth subs as this was missing.
*Assortment of perfomance improvements

* poloniex pass

* send all trades to data handler, validated enabled and disable pairs

* initial clean

* centralised request matching mechanism

* websocket main improvements WIP

* WIP

* Websocket management via gctcli WIP

* GRPC expansion

* Updated GCTCLI with websocket url and proxy setting functionality which flushes connection

* Fix continuous spawning of routines bug on error with reconnection

* Addr linter issues

* fix subscription bug that I caused when I changed to a switch case

* fix linter issue

* fix woopsie

* End of day WIP

* Fix order submission REST, time conversion, order type conversion, orderID bugs

* fix gateio test and unsubscribe bug

* revert comment out code

* websocketAPI changed to to true in configtest.json

* fix race in gateio test

* End of day WIP for websocket tests.

* BugFix for binance when book isn't seeded. Updated websocket tests. Deprecated subscription manager. RM wrapper funcs.

* Added string title to exchange name as they are saved as lower case in type, reinstated verbose check in websocket.go

* Added verbosity check for setting websocket URL

* fix bug where the asset had a mind of its own

* purge dodgy coding

* Fix tests, drop blocking chan in websocket Dial function

* few more changes

* race condition fix for websocket tests.

* fix intermittent test failure due to underlying hash table storage

* Address madcuzbad nit

* RM superfluous printlines

* Add quick top example with paramater fields

* First pass Glorious nits

* As per madcozbad suggestion return error when enabled pair not found in full return map. Add test.

* addr madcozbadd nits

* as per glorious suggestion rm'd loadedJSON field

* adjusted ticker, added test and RM'd code that can never be executed

* Addr nits and add in crypto rand genration for ID's

* remove global channel declaration and rescoped as this was causing a lock

* as per glorious suggestion restructured return error for websocket

* addr glorious suggestions

* fix linter issues

* purge non-existent pair from testdata

* add side field to struct and parse

* addr glorious nits

* Add verbosity to error returns and logs and fix string parsing in GCTRPC

* fix speeling mistwake

* Adds websocket functionality check before flushing websocket connection

* Addr kraken panic and setting/flush websocket url stage one.

* added websocket url check before setting with tests

* Added in edge case test if by the time we call contains on available pairs it has been changed

* remove error return for func

* Continuation of tests

* continuation of tests

* Stop potential panic within pair creation function

* Implement changes to upstream

* rm sup comment

* fix bug when subscribing and unsubscribing. Also add in boolean to determine there are currencies that need to be flushed via set pairs via gctcli

* fix test

* Fix linter issues

* Fix tests

* turn websocket off in config example

* Fix issue where you cannot enable websocket when config is set to false, also added config websocket enable state saving

* Introduced err var for same error returns

* Add err var exchange base not found

* restructure function

* drop gctscript from generic response name

* drop managesub delay const as its not being used

* correctly implement websocket rate limiting for coinut

* remove quotations

* drop pair management check

* fix spelling

* return error in function to not update currency with unset role

* amalagamted enable/disable into set function and added in pairstore fetch function

* update error description

* rm function

* moved test function to sharedtestvals and move type to types.go

* append delimiter onto currency delimiter strings

* add test coverage

* rm functions as they are set as methods in base

* remove superfluous methods

* Fix issue that would occur when a subscription errored and not appending successful subs

* fix after rebase woopsie

* fix linter issues

* fix bug streamline code

* fix linter issues

* fix linter issues

* fix case where it should not change ID if set but append new

* fix whoopsie

* fix websocket tests

* fix readme, fix wrapper issues reporting template, go mod tidy

* add test coverage

* add test coverage and verified futures pariing

* add in futures bypass as its not currently supported on BTSE until API update and implementation

* removed downside/upside profit contract type as its no longer supported. Added in check in set config pairs to warn user of potential conflict and to manually remove or update.

* If asset enabled add pair and increase code coverage

* remove strings.title, set and fetch with strings.Lower but keep struct field exchangename unchanged. Streamline ticker and orderbook code.

* Add code coverage

* log error if setting default currency fails, add code coverage

* address glorious nits

* Addr xtda nits

* fix linter issues

* addr glorious nits

* xtda nits

* Addr glorious nits

* add subscription protection and removed a superfluous wait call

* fix test

* fix whoopsie

* addr xtda nits

* addr glorious nits

* Added asset types to subscriptions structs, also added in error handling for resubscription errors

* consolidated rpc returned type and added in sucessful strings

* dropped stream timing down to 100ms

* DOC changes

* proxy and url usage string additions

* WIP

* go mod tidy rides again

* Addr nits

* Addr nits, fix tests

* fix wording

* add in test case for currency matching

* Add byte length check on outbound websocket payload subscriptions

* addr thrasher nits

* Addr madcozbadd nits

* addr linter issues

* Addr glorious nits by amalgamating function into one mega amazing function.

* fix futures account subscription bug

* addr glorious nits and reinstated wg.Wait() checks

* changed string to currency delimiter string and setconnected by function
2020-07-24 13:18:09 +10:00

634 lines
16 KiB
Go

package hitbtc
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
const (
// API
apiURL = "https://api.hitbtc.com"
// Public
apiV2Trades = "api/2/public/trades"
apiV2Currency = "api/2/public/currency"
apiV2Symbol = "api/2/public/symbol"
apiV2Ticker = "api/2/public/ticker"
apiV2Orderbook = "api/2/public/orderbook"
apiV2Candles = "api/2/public/candles"
// Authenticated
apiV2Balance = "api/2/trading/balance"
apiV2CryptoAddress = "api/2/account/crypto/address"
apiV2CryptoWithdraw = "api/2/account/crypto/withdraw"
apiV2TradeHistory = "api/2/history/trades"
apiV2OrderHistory = "api/2/history/order"
apiv2OpenOrders = "api/2/order"
apiV2FeeInfo = "api/2/trading/fee"
orders = "order"
apiOrder = "api/2/order"
orderMove = "moveOrder"
tradableBalances = "returnTradableBalances"
transferBalance = "transferBalance"
)
// HitBTC is the overarching type across the hitbtc package
type HitBTC struct {
exchange.Base
}
// Public Market Data
// https://api.hitbtc.com/?python#market-data
// GetCurrencies returns the actual list of available currencies, tokens, ICO
// etc.
func (h *HitBTC) GetCurrencies() (map[string]Currencies, error) {
type Response struct {
Data []Currencies
}
resp := Response{}
path := fmt.Sprintf("%s/%s", h.API.Endpoints.URL, apiV2Currency)
ret := make(map[string]Currencies)
err := h.SendHTTPRequest(path, &resp.Data)
if err != nil {
return ret, err
}
for _, id := range resp.Data {
ret[id.ID] = id
}
return ret, err
}
// GetCurrency returns the actual list of available currencies, tokens, ICO
// etc.
func (h *HitBTC) GetCurrency(currency string) (Currencies, error) {
type Response struct {
Data Currencies
}
resp := Response{}
path := fmt.Sprintf("%s/%s/%s", h.API.Endpoints.URL, apiV2Currency, currency)
return resp.Data, h.SendHTTPRequest(path, &resp.Data)
}
// GetSymbols Return the actual list of currency symbols (currency pairs) traded
// on HitBTC exchange. The first listed currency of a symbol is called the base
// 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) {
var resp []Symbol
path := fmt.Sprintf("%s/%s/%s", h.API.Endpoints.URL, apiV2Symbol, symbol)
ret := make([]string, 0, len(resp))
err := h.SendHTTPRequest(path, &resp)
if err != nil {
return ret, err
}
for _, x := range resp {
ret = append(ret, x.ID)
}
return ret, err
}
// GetSymbolsDetailed is the same as above but returns an array of symbols with
// all their details.
func (h *HitBTC) GetSymbolsDetailed() ([]Symbol, error) {
var resp []Symbol
path := fmt.Sprintf("%s/%s", h.API.Endpoints.URL, apiV2Symbol)
return resp, h.SendHTTPRequest(path, &resp)
}
// GetTicker returns ticker information
func (h *HitBTC) GetTicker(symbol string) (TickerResponse, error) {
var resp TickerResponse
path := fmt.Sprintf("%s/%s/%s", h.API.Endpoints.URL, apiV2Ticker, symbol)
return resp, h.SendHTTPRequest(path, &resp)
}
// GetTickers returns ticker information
func (h *HitBTC) GetTickers() ([]TickerResponse, error) {
var resp []TickerResponse
path := fmt.Sprintf("%s/%s/", h.API.Endpoints.URL, apiV2Ticker)
return resp, h.SendHTTPRequest(path, &resp)
}
// GetTrades returns trades from hitbtc
func (h *HitBTC) GetTrades(currencyPair, from, till, limit, offset, by, sort string) ([]TradeHistory, error) {
// start Number or Datetime
// end Number or Datetime
// limit Number
// offset Number
// by Filtration definition. Accepted values: id, timestamh. Default timestamp
// sort Default DESC
vals := url.Values{}
if from != "" {
vals.Set("from", from)
}
if till != "" {
vals.Set("till", till)
}
if limit != "" {
vals.Set("limit", limit)
}
if offset != "" {
vals.Set("offset", offset)
}
if by != "" {
vals.Set("by", by)
}
if sort != "" {
vals.Set("sort", sort)
}
var resp []TradeHistory
path := fmt.Sprintf("%s/%s/%s?%s",
h.API.Endpoints.URL,
apiV2Trades,
currencyPair,
vals.Encode())
return resp, h.SendHTTPRequest(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) {
// limit Limit of orderbook levels, default 100. Set 0 to view full orderbook levels
vals := url.Values{}
if limit != 0 {
vals.Set("limit", strconv.Itoa(limit))
}
resp := OrderbookResponse{}
path := fmt.Sprintf("%s/%s/%s?%s",
h.API.Endpoints.URL,
apiV2Orderbook,
currencyPair,
vals.Encode())
err := h.SendHTTPRequest(path, &resp)
if err != nil {
return Orderbook{}, err
}
ob := Orderbook{}
ob.Asks = append(ob.Asks, resp.Asks...)
ob.Bids = append(ob.Bids, resp.Bids...)
return ob, nil
}
// 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) {
// 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{}
if limit != "" {
vals.Set("limit", limit)
}
if period != "" {
vals.Set("period", period)
}
if !end.IsZero() && start.After(end) {
return nil, errors.New("start time cannot be after end time")
}
if !start.IsZero() {
vals.Set("from", start.Format(time.RFC3339))
}
if !end.IsZero() {
vals.Set("till", end.Format(time.RFC3339))
}
var resp []ChartData
path := fmt.Sprintf("%s/%s/%s?%s", h.API.Endpoints.URL, apiV2Candles, currencyPair, vals.Encode())
return resp, h.SendHTTPRequest(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) {
var result []Balance
err := h.SendAuthenticatedHTTPRequest(http.MethodGet,
apiV2Balance,
url.Values{},
otherRequests,
&result)
ret := make(map[string]Balance)
if err != nil {
return ret, err
}
for _, item := range result {
ret[item.Currency] = item
}
return ret, nil
}
// GetDepositAddresses returns a deposit address for a specific currency
func (h *HitBTC) GetDepositAddresses(currency string) (DepositCryptoAddresses, error) {
var resp DepositCryptoAddresses
return resp,
h.SendAuthenticatedHTTPRequest(http.MethodGet,
apiV2CryptoAddress+"/"+currency,
url.Values{},
otherRequests,
&resp)
}
// GenerateNewAddress generates a new deposit address for a currency
func (h *HitBTC) GenerateNewAddress(currency string) (DepositCryptoAddresses, error) {
resp := DepositCryptoAddresses{}
err := h.SendAuthenticatedHTTPRequest(http.MethodPost,
apiV2CryptoAddress+"/"+currency,
url.Values{},
otherRequests,
&resp)
return resp, err
}
// GetActiveorders returns all your active orders
func (h *HitBTC) GetActiveorders(currency string) ([]Order, error) {
var resp []Order
err := h.SendAuthenticatedHTTPRequest(http.MethodGet,
orders+"?symbol="+currency,
url.Values{},
tradingRequests,
&resp)
return resp, err
}
// GetTradeHistoryForCurrency returns your trade history
func (h *HitBTC) GetTradeHistoryForCurrency(currency, start, end string) (AuthenticatedTradeHistoryResponse, error) {
values := url.Values{}
if start != "" {
values.Set("start", start)
}
if end != "" {
values.Set("end", end)
}
values.Set("currencyPair", currency)
result := AuthenticatedTradeHistoryResponse{}
return result, h.SendAuthenticatedHTTPRequest(http.MethodPost,
apiV2TradeHistory,
values,
otherRequests,
&result.Data)
}
// GetTradeHistoryForAllCurrencies returns your trade history
func (h *HitBTC) GetTradeHistoryForAllCurrencies(start, end string) (AuthenticatedTradeHistoryAll, error) {
values := url.Values{}
if start != "" {
values.Set("start", start)
}
if end != "" {
values.Set("end", end)
}
values.Set("currencyPair", "all")
result := AuthenticatedTradeHistoryAll{}
return result, h.SendAuthenticatedHTTPRequest(http.MethodPost,
apiV2TradeHistory,
values,
otherRequests,
&result.Data)
}
// GetOrders List of your order history.
func (h *HitBTC) GetOrders(currency string) ([]OrderHistoryResponse, error) {
values := url.Values{}
values.Set("symbol", currency)
var result []OrderHistoryResponse
return result, h.SendAuthenticatedHTTPRequest(http.MethodGet,
apiV2OrderHistory,
values,
tradingRequests,
&result)
}
// GetOpenOrders List of your currently open orders.
func (h *HitBTC) GetOpenOrders(currency string) ([]OrderHistoryResponse, error) {
values := url.Values{}
values.Set("symbol", currency)
var result []OrderHistoryResponse
return result, h.SendAuthenticatedHTTPRequest(http.MethodGet,
apiv2OpenOrders,
values,
tradingRequests,
&result)
}
// PlaceOrder places an order on the exchange
func (h *HitBTC) PlaceOrder(currency string, rate, amount float64, orderType, side string) (OrderResponse, error) {
var result OrderResponse
values := url.Values{}
values.Set("symbol", currency)
values.Set("rate", strconv.FormatFloat(rate, 'f', -1, 64))
values.Set("quantity", strconv.FormatFloat(amount, 'f', -1, 64))
values.Set("side", side)
values.Set("price", strconv.FormatFloat(rate, 'f', -1, 64))
values.Set("type", orderType)
return result, h.SendAuthenticatedHTTPRequest(http.MethodPost,
apiOrder,
values,
tradingRequests,
&result)
}
// CancelExistingOrder cancels a specific order by OrderID
func (h *HitBTC) CancelExistingOrder(orderID int64) (bool, error) {
result := GenericResponse{}
values := url.Values{}
err := h.SendAuthenticatedHTTPRequest(http.MethodDelete,
apiOrder+"/"+strconv.FormatInt(orderID, 10),
values,
tradingRequests,
&result)
if err != nil {
return false, err
}
if result.Success != 1 {
return false, errors.New(result.Error)
}
return true, nil
}
// CancelAllExistingOrders cancels all open orders
func (h *HitBTC) CancelAllExistingOrders() ([]Order, error) {
var result []Order
values := url.Values{}
return result, h.SendAuthenticatedHTTPRequest(http.MethodDelete,
apiOrder,
values,
tradingRequests,
&result)
}
// MoveOrder generates a new move order
func (h *HitBTC) 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))
if amount != 0 {
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
}
err := h.SendAuthenticatedHTTPRequest(http.MethodPost,
orderMove,
values,
tradingRequests,
&result)
if err != nil {
return result, err
}
if result.Success != 1 {
return result, errors.New(result.Error)
}
return result, nil
}
// Withdraw allows for the withdrawal to a specific address
func (h *HitBTC) Withdraw(currency, address string, amount float64) (bool, error) {
result := Withdraw{}
values := url.Values{}
values.Set("currency", currency)
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
values.Set("address", address)
err := h.SendAuthenticatedHTTPRequest(http.MethodPost,
apiV2CryptoWithdraw,
values,
otherRequests,
&result)
if err != nil {
return false, err
}
if result.Error != "" {
return false, errors.New(result.Error)
}
return true, nil
}
// GetFeeInfo returns current fee information
func (h *HitBTC) GetFeeInfo(currencyPair string) (Fee, error) {
result := Fee{}
err := h.SendAuthenticatedHTTPRequest(http.MethodGet,
apiV2FeeInfo+"/"+currencyPair,
url.Values{},
tradingRequests,
&result)
return result, err
}
// GetTradableBalances returns current tradable balances
func (h *HitBTC) GetTradableBalances() (map[string]map[string]float64, error) {
type Response struct {
Data map[string]map[string]interface{}
}
result := Response{}
err := h.SendAuthenticatedHTTPRequest(http.MethodPost,
tradableBalances,
url.Values{},
tradingRequests,
&result.Data)
if err != nil {
return nil, err
}
balances := make(map[string]map[string]float64)
for x, y := range result.Data {
balances[x] = make(map[string]float64)
for z, w := range y {
balances[x][z], _ = strconv.ParseFloat(w.(string), 64)
}
}
return balances, nil
}
// TransferBalance transfers a balance
func (h *HitBTC) TransferBalance(currency, from, to string, amount float64) (bool, error) {
values := url.Values{}
result := GenericResponse{}
values.Set("currency", currency)
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
values.Set("fromAccount", from)
values.Set("toAccount", to)
err := h.SendAuthenticatedHTTPRequest(http.MethodPost,
transferBalance,
values,
otherRequests,
&result)
if err != nil {
return false, err
}
if result.Error != "" && result.Success != 1 {
return false, errors.New(result.Error)
}
return true, nil
}
// SendHTTPRequest sends an unauthenticated HTTP request
func (h *HitBTC) SendHTTPRequest(path string, result interface{}) error {
return h.SendPayload(context.Background(), &request.Item{
Method: http.MethodGet,
Path: path,
Result: result,
Verbose: h.Verbose,
HTTPDebugging: h.HTTPDebugging,
HTTPRecording: h.HTTPRecording,
Endpoint: marketRequests,
})
}
// SendAuthenticatedHTTPRequest sends an authenticated http request
func (h *HitBTC) SendAuthenticatedHTTPRequest(method, endpoint string, values url.Values, f request.EndpointLimit, result interface{}) error {
if !h.AllowAuthenticatedRequest() {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
h.Name)
}
headers := make(map[string]string)
headers["Authorization"] = "Basic " + crypto.Base64Encode([]byte(h.API.Credentials.Key+":"+h.API.Credentials.Secret))
path := fmt.Sprintf("%s/%s", h.API.Endpoints.URL, endpoint)
return h.SendPayload(context.Background(), &request.Item{
Method: method,
Path: path,
Headers: headers,
Body: bytes.NewBufferString(values.Encode()),
Result: result,
AuthRequest: true,
Verbose: h.Verbose,
HTTPDebugging: h.HTTPDebugging,
HTTPRecording: h.HTTPRecording,
Endpoint: f,
})
}
// GetFee returns an estimate of fee based on type of transaction
func (h *HitBTC) GetFee(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())
if err != nil {
return 0, err
}
fee = calculateTradingFee(feeInfo, feeBuilder.PurchasePrice,
feeBuilder.Amount,
feeBuilder.IsMaker)
case exchange.CryptocurrencyWithdrawalFee:
currencyInfo, err := h.GetCurrency(feeBuilder.Pair.Base.String())
if err != nil {
return 0, err
}
fee, err = strconv.ParseFloat(currencyInfo.PayoutFee, 64)
if err != nil {
return 0, err
}
case exchange.CyptocurrencyDepositFee:
fee = calculateCryptocurrencyDepositFee(feeBuilder.Pair.Base,
feeBuilder.Amount)
case exchange.OfflineTradeFee:
fee = getOfflineTradeFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
}
if fee < 0 {
fee = 0
}
return fee, nil
}
// getOfflineTradeFee calculates the worst case-scenario trading fee
func getOfflineTradeFee(price, amount float64) float64 {
return 0.002 * price * amount
}
func calculateCryptocurrencyDepositFee(c currency.Code, amount float64) float64 {
var fee float64
if c == currency.BTC {
fee = 0.0006
}
return fee * amount
}
func calculateTradingFee(feeInfo Fee, purchasePrice, amount float64, isMaker bool) float64 {
var volumeFee float64
if isMaker {
volumeFee = feeInfo.ProvideLiquidityRate
} else {
volumeFee = feeInfo.TakeLiquidityRate
}
return volumeFee * amount * purchasePrice
}