Files
gocryptotrader/exchanges/hitbtc/hitbtc.go
Scott 80bc8c7e9e Trade history, recent trades, live trade processing and storage (#558)
* End of day commit moving packages and setting foundation into how trade processing will go

* Conformity

* tdd candle generation based on received trade data, renames orderbookbuffer back to buffer for now...

* Formalises test functions and designs the trade processor

* Theoretical amending old candles to allow any trades that were part of an old processed candle to be more accurate. Saving of candles will only occur on previous cycles, extending memory usage a bit longer

* Figures out sqlboiler for sqlite. Updates websocket entries to process trade data

* One more trade data

* Adds more exchange support

* Adds PSQL stuff

* Begins creating sql implementation

* End of day commit. Helper functions and understanding sql usage in GCT

* Adds delete and cleans up table design

* Finishes trades conceptually. Awaits candle data update in order to translate trades to candles

* Initial handling of trades in coinbene

* Proto

* Fixing of some bugs, attempting to address coinbene asset type ws issues

* Fixes up coinbene websocket implementation for the most part

* finalises coinbene websocket implementation. Adds new ability to parse currencies without a delimiter

* Implements rpc commands and adds testing

* updates the following to be compatible with trade data update: Theoretical amending old candles to allow any trades that were part of an old processed candle to be more accurate. Saving of candles will only occur on previous cycles, extending memory usage a bit longer

* Changes trade to be its own entity rather than attached to a websocket.

* Adds coverage to trades. Changes signature of `AddTradesToBuffer` to return error. Now automatically shuts down without need for channel listening. Will automatically start up again if it gets data

* Implements trade fetching at the wrapper level for a bunch of exchanges. Adds trade id to script updoot. Probably breaking change

* Implements trade fetching for all wrappers hurray hurrah. Updates all the tests

* Adds new interface func to get recent trades. Ensures GetExchangeHistory continues until conditions are met

* Adds new readme, tests all new wrapper endpoints, updates exchange_wrapper_issues to test new endpoints. Updates exchange_wrapper_coverage with new coverage... Fixes lame bug causing wrapper tests to fail from being poorly setup. Adds loopy loop to ensure that all data is captured when requesting exchange history

* Bugfix on psql migrations. Rebases latest changes, updates table design to use base and quote, updates trades to use exchange_name_id

* Adds new config field for saving trades to the database per exchange. Now exits trade processing when trade saving is not enabled. Similarly for wrapper, does not save if not enabled

* Minor bitfinex trade fixes. continues on buffer processing errors, now saves transactionid to the db

* Adds support for generating candles from candlesextended. May extend it further, idk

* Updates trade candles to be able to fill missing data with trades. Adds more tests. Also does a thing where you can forcefully override a candle based on internal trade data instead of API data

* Fixes bug where force deletions did not follow up with insertions. Adds force to candle commands

* Fixes specific exchange based issues. Extends recent trades to 24 hours where possible

* Fixes issue with saved tests. Fixes tests for trades. Adds parallel to tests. Pre-fixes people's nits

* Adds new GRPC functions to find out what data is missing from trades and candles. Fixes some assumptions from missing period code.

* Adds unique constraint. Fixes up niggling issues for wrappers and websockets

* Fixes issues with using unix times in the database trying to retrieve data via the CLI. Reduces save time to 15 seconds

* Updates trades to use timestamps instead of int64 unix

* Adds missing FTX wrapper implementation. Regens docs

* Linting the linters. Updating readme

* Adds new command to set whether an exchange can process trades

* Doc update

* Adds recent trades and historic trade endpoints to grpc

* formats pair_test.go to appease linter gods

* Addresses data race. Removes logging of missing intervals on unrelated function (now that it has its own rpc command). The buffer time isnt customisable, but I don't feel it needs to be at a config level at all really.

* Fixes a few niterinos regarding spacing, type conversion, a weird Bitmex 0 trade value error, unsubscriptions and cli command references

* Reduces map lookups. Adds base func and moves wrappers to use it

* Uses better currency formatter. Adds time based validation to trade history. Reverts configtest.json

* Reverts config and updates test names. Also WAYYYYY LESS SPAMMY

* oopsie doopsie missed a whoopsie

* mint flavoured lint

* Fixes issues caused by rebase

* Fixes issue with timestamps not converting properly from command to RPCServer. Adds new error type. Adds shorthand entries to some commands. Removes os.Exit from tests. Makes Gemini test rolling. Adds enabled exchange check to RPC function. Escapes timestamp on bitstamp. Renames var

* fixes whoopsie oopsie doopsie I forgot to remove code shoopsie

* missed a line

* 🎉 🎉 :tada:Breaks everything in an end of day commit 🎉 🎉 🎉

* Modifies function 'createlocaloffset' to return a string instead. Uses strings for all time based start and end commands. Uses UTC times in RPC server and updates SQLITE to use formatted time based queries

* Adds concurrency-safe way of changing SaveTradeData and checking it. Fixes embarrassing typo

* End of day fix, adds bitfinex update to loop until either the return trades shows no new dates, or meets specifications. Fixes egregious typo

* Improves testing and handling of historical trades function

* Fixes tests after latest changes

* Fix potential fatal err now that db is enabled in test config now

* Fixes up some database settings to use a local engine instead of global var

* DELICIOUS LINT CHOCOLATE FIXES

* Fixes data race by slashing competitor's tyres

* Adds mock test fixes to allow for live and stored data test

* Removes verbosity in engine level tests. Adds new timezone format to highlight the timezone for RPC functions. Removes reference to Preix index fund

* Oopsie doopsie, fixed a whoopsie

* Loggers can no longer do data drag races on my lawn 👴

* Removes bad lock

* Addresses command nits. End of day conceptual commit, trying to calculate spans of time in the context of missing periods. Tests will fail

* Adds new stream response for retrieving trade history as it can take time to do. Unsuccessfully attempts to simplify time range calculation for missing trades response

* Adds new timeperiods package to calculate time periods, time ranges and whether data is in those ranges. Removes kline basic implementation of same concept

* Fixes lint issues. Fixes test. Moves trade cli commands to their own trade subcommands

* Updates lakebtc to no longer have gethistorictrades as it is unsupported. Adds more validation to rpc functions

* Removes requirement to have trades when testing trade wrapper functions. Doesn't really prove it works if there are no trades for a given currency in a time period.

* Addresses nits, runs linting fix and ensures a test is consistent

* Fix merge issues

* Moves sort to timeperiods. Adds test coverage. Fixes typo

* Removes log package in CLI

* Fixes `GetTrades` url

* Reorders all instances of validation occuring after settingup RPC connection

* Fixes test to ensure that it is setup before testing that it is setup

* Fixed issue with bool retrieval. Removes double append

* Fixes Binance times, fixes bitfinex sell sides, fixes huobi times, sorts all responses

* Fixes poloniex trade id consistency. Makes recent trade for poloniex consistent with others (15 minutes). Fixes coinbene. Fixes localbitcoins to use quote currency. Fixes coinut times. Updates huobi trade id, saves okgroup trades. Fixes bid and ask to buy and sell

* Removes websocket trades for lakebtc as it did not meet our requirements for processing. Adds new constraints to the database to ensure we have uniqueness on trades where ID doesn't exist and doesn't trigger errors for trades where the tid does

* Fixes migration for postgres to downscale properly

* Really really fixes the psql index changes

* Fixes broken tests

* Now with working tests and no pocket lint

* Makes the side column nullable with no more constraint for it. adds migrations and runs generation. comments lakebtc

* Lint & Sprüngli

* Updates zb to use more appropriate side

* Fixes oopsie

* Attempts to address a data race from globals

* Fixes build

* Fixes missed regen rpc files

* Updates readme to point to trade readme. Fixes exchange_wrapper_coverage wrapper count and untested panics, tests bitfinex funding pair test for `fUSD`, adds shiny new param `tradeprocessinginterval`

* mint flavoured lint

* Uses the real default to set the default value by default

* Fixes some extra tests surrounding email sending and number incompatibility

* Reverts test config

* re-adds gom2/usdt currency

* Fixes typo, don't look!

* Fixes minor codelingo pickups

* Adds more precision to handling of trade data from Kraken. Expands test

* interface christmas tree

* lint
2020-10-29 13:00:02 +11:00

622 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, by, sort string, from, till, limit, offset int64) ([]TradeHistory, error) {
urlValues := url.Values{}
if from > 0 {
urlValues.Set("from", strconv.FormatInt(from, 10))
}
if till > 0 {
urlValues.Set("till", strconv.FormatInt(till, 10))
}
if limit > 0 {
urlValues.Set("limit", strconv.FormatInt(limit, 10))
}
if offset > 0 {
urlValues.Set("offset", strconv.FormatInt(offset, 10))
}
if by != "" {
urlValues.Set("by", by)
}
if sort != "" {
urlValues.Set("sort", sort)
}
var resp []TradeHistory
path := fmt.Sprintf("%s/%s/%s?%s",
h.API.Endpoints.URL,
apiV2Trades,
currencyPair,
urlValues.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
}