Files
gocryptotrader/exchanges/btse/btse.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

591 lines
17 KiB
Go

package btse
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"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/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/log"
)
// BTSE is the overarching type across this package
type BTSE struct {
exchange.Base
}
const (
btseAPIURL = "https://api.btse.com"
btseSPOTPath = "/spot"
btseSPOTAPIPath = "/api/v3.2/"
btseFuturesPath = "/futures"
btseFuturesAPIPath = "/api/v2.1/"
// Public endpoints
btseMarketOverview = "market_summary"
btseOrderbook = "orderbook"
btseTrades = "trades"
btseTime = "time"
btseOHLCV = "ohlcv"
btsePrice = "price"
// Authenticated endpoints
btseWallet = "user/wallet"
btseWalletHistory = "user/wallet_history"
btseWalletAddress = "user/wallet/address"
btseWalletWithdrawal = "user/wallet/withdraw"
btseExchangeHistory = "user/trade_history"
btseUserFee = "user/fees"
btseOrder = "order"
btsePegOrder = "order/peg"
btsePendingOrders = "user/open_orders"
btseCancelAllAfter = "order/cancelAllAfter"
)
// GetMarketSummary stores market summary data
func (b *BTSE) GetMarketSummary(symbol string, spot bool) (MarketSummary, error) {
var m MarketSummary
path := btseMarketOverview
if symbol != "" {
path += "?symbol=" + url.QueryEscape(symbol)
}
return m, b.SendHTTPRequest(http.MethodGet, path, &m, spot, queryFunc)
}
// FetchOrderBook gets orderbook data for a given pair
func (b *BTSE) FetchOrderBook(symbol string, group, limitBids, limitAsks int, spot bool) (*Orderbook, error) {
var o Orderbook
urlValues := url.Values{}
urlValues.Add("symbol", symbol)
if limitBids > 0 {
urlValues.Add("limit_bids", strconv.Itoa(limitBids))
}
if limitAsks > 0 {
urlValues.Add("limit_asks", strconv.Itoa(limitAsks))
}
if group > 0 {
urlValues.Add("group", strconv.Itoa(group))
}
return &o, b.SendHTTPRequest(http.MethodGet,
common.EncodeURLValues(btseOrderbook, urlValues), &o, spot, queryFunc)
}
// FetchOrderBookL2 retrieve level 2 orderbook for requested symbol and depth
func (b *BTSE) FetchOrderBookL2(symbol string, depth int) (*Orderbook, error) {
var o Orderbook
urlValues := url.Values{}
urlValues.Add("symbol", symbol)
urlValues.Add("depth", strconv.FormatInt(int64(depth), 10))
endpoint := common.EncodeURLValues(btseOrderbook+"/L2", urlValues)
return &o, b.SendHTTPRequest(http.MethodGet, endpoint, &o, true, queryFunc)
}
// GetTrades returns a list of trades for the specified symbol
func (b *BTSE) GetTrades(symbol string, start, end time.Time, beforeSerialID, afterSerialID, count int, includeOld, spot bool) ([]Trade, error) {
var t []Trade
urlValues := url.Values{}
urlValues.Add("symbol", symbol)
if count > 0 {
urlValues.Add("count", strconv.Itoa(count))
}
if !start.IsZero() {
urlValues.Add("start", strconv.FormatInt(start.Unix(), 10))
}
if !end.IsZero() {
urlValues.Add("end", strconv.FormatInt(end.Unix(), 10))
}
if !start.IsZero() && !end.IsZero() && start.After(end) {
return t, errors.New("start cannot be after end time")
}
if beforeSerialID > 0 {
urlValues.Add("beforeSerialId", strconv.Itoa(beforeSerialID))
}
if afterSerialID > 0 {
urlValues.Add("afterSerialId", strconv.Itoa(afterSerialID))
}
if includeOld {
urlValues.Add("includeOld", "true")
}
return t, b.SendHTTPRequest(http.MethodGet,
common.EncodeURLValues(btseTrades, urlValues), &t, spot, queryFunc)
}
// OHLCV retrieve and return OHLCV candle data for requested symbol
func (b *BTSE) OHLCV(symbol string, start, end time.Time, resolution int) (OHLCV, error) {
var o OHLCV
urlValues := url.Values{}
urlValues.Add("symbol", symbol)
if !start.IsZero() && !end.IsZero() {
if start.After(end) {
return o, errors.New("start cannot be after end time")
}
urlValues.Add("start", strconv.FormatInt(start.Unix(), 10))
urlValues.Add("end", strconv.FormatInt(end.Unix(), 10))
}
var res = 60
if resolution != 0 {
res = resolution
}
urlValues.Add("resolution", strconv.FormatInt(int64(res), 10))
endpoint := common.EncodeURLValues(btseOHLCV, urlValues)
return o, b.SendHTTPRequest(http.MethodGet, endpoint, &o, true, queryFunc)
}
// GetPrice get current price for requested symbol
func (b *BTSE) GetPrice(symbol string) (Price, error) {
var p Price
path := btsePrice + "?symbol=" + url.QueryEscape(symbol)
return p, b.SendHTTPRequest(http.MethodGet, path, &p, true, queryFunc)
}
// GetServerTime returns the exchanges server time
func (b *BTSE) GetServerTime() (*ServerTime, error) {
var s ServerTime
return &s, b.SendHTTPRequest(http.MethodGet, btseTime, &s, true, queryFunc)
}
// GetWalletInformation returns the users account balance
func (b *BTSE) GetWalletInformation() ([]CurrencyBalance, error) {
var a []CurrencyBalance
return a, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseWallet, true, nil, nil, &a, queryFunc)
}
// GetFeeInformation retrieve fee's (maker/taker) for requested symbol
func (b *BTSE) GetFeeInformation(symbol string) ([]AccountFees, error) {
var resp []AccountFees
urlValues := url.Values{}
if symbol != "" {
urlValues.Add("symbol", symbol)
}
return resp, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseUserFee, true, urlValues, nil, &resp, queryFunc)
}
// GetWalletHistory returns the users account balance
func (b *BTSE) GetWalletHistory(symbol string, start, end time.Time, count int) (WalletHistory, error) {
var resp WalletHistory
urlValues := url.Values{}
if symbol != "" {
urlValues.Add("symbol", symbol)
}
if !start.IsZero() && !end.IsZero() {
if start.After(end) || end.Before(start) {
return resp, errors.New("start cannot be after end time")
}
urlValues.Add("start", strconv.FormatInt(start.Unix(), 10))
urlValues.Add("end", strconv.FormatInt(end.Unix(), 10))
}
if count > 0 {
urlValues.Add("count", strconv.Itoa(count))
}
return resp, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseWalletHistory, true, urlValues, nil, &resp, queryFunc)
}
// GetWalletAddress returns the users account balance
func (b *BTSE) GetWalletAddress(currency string) (WalletAddress, error) {
var resp WalletAddress
urlValues := url.Values{}
if currency != "" {
urlValues.Add("currency", currency)
}
return resp, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseWalletAddress, true, urlValues, nil, &resp, queryFunc)
}
// CreateWalletAddress create new deposit address for requested currency
func (b *BTSE) CreateWalletAddress(currency string) (WalletAddress, error) {
var resp WalletAddress
req := make(map[string]interface{}, 1)
req["currency"] = currency
err := b.SendAuthenticatedHTTPRequest(http.MethodPost, btseWalletAddress, true, nil, req, &resp, queryFunc)
if err != nil {
errResp := ErrorResponse{}
errResponseStr := strings.Split(err.Error(), "raw response: ")
err := json.Unmarshal([]byte(errResponseStr[1]), &errResp)
if err != nil {
return resp, err
}
if errResp.ErrorCode == 3528 {
walletAddress := strings.Split(errResp.Message, "BADREQUEST: ")
return WalletAddress{
{
Address: walletAddress[1],
},
}, nil
}
return resp, err
}
return resp, nil
}
// WalletWithdrawal submit request to withdraw crypto currency
func (b *BTSE) WalletWithdrawal(currency, address, tag, amount string) (WithdrawalResponse, error) {
var resp WithdrawalResponse
req := make(map[string]interface{}, 4)
req["currency"] = currency
req["address"] = address
req["tag"] = tag
req["amount"] = amount
return resp, b.SendAuthenticatedHTTPRequest(http.MethodPost, btseWalletWithdrawal, true, nil, req, &resp, queryFunc)
}
// CreateOrder creates an order
func (b *BTSE) CreateOrder(clOrderID string, deviation float64, postOnly bool, price float64, side string, size, stealth, stopPrice float64, symbol, timeInForce string, trailValue, triggerPrice float64, txType, orderType string) ([]Order, error) {
req := make(map[string]interface{})
if clOrderID != "" {
req["clOrderID"] = clOrderID
}
if deviation > 0.0 {
req["deviation"] = deviation
}
if postOnly {
req["postOnly"] = postOnly
}
if price > 0.0 {
req["price"] = price
}
if side != "" {
req["side"] = side
}
if size > 0.0 {
req["size"] = size
}
if stealth > 0.0 {
req["stealth"] = stealth
}
if stopPrice > 0.0 {
req["stopPrice"] = stopPrice
}
if symbol != "" {
req["symbol"] = symbol
}
if timeInForce != "" {
req["time_in_force"] = timeInForce
}
if trailValue > 0.0 {
req["trailValue"] = trailValue
}
if triggerPrice > 0.0 {
req["triggerPrice"] = triggerPrice
}
if txType != "" {
req["txType"] = txType
}
if orderType != "" {
req["type"] = orderType
}
var r []Order
return r, b.SendAuthenticatedHTTPRequest(http.MethodPost, btseOrder, true, url.Values{}, req, &r, orderFunc)
}
// GetOrders returns all pending orders
func (b *BTSE) GetOrders(symbol, orderID, clOrderID string) ([]OpenOrder, error) {
req := url.Values{}
if orderID != "" {
req.Add("orderID", orderID)
}
req.Add("symbol", symbol)
if clOrderID != "" {
req.Add("clOrderID", clOrderID)
}
var o []OpenOrder
return o, b.SendAuthenticatedHTTPRequest(http.MethodGet, btsePendingOrders, true, req, nil, &o, orderFunc)
}
// CancelExistingOrder cancels an order
func (b *BTSE) CancelExistingOrder(orderID, symbol, clOrderID string) (CancelOrder, error) {
var c CancelOrder
req := url.Values{}
if orderID != "" {
req.Add("orderID", orderID)
}
req.Add("symbol", symbol)
if clOrderID != "" {
req.Add("clOrderID", clOrderID)
}
return c, b.SendAuthenticatedHTTPRequest(http.MethodDelete, btseOrder, true, req, nil, &c, orderFunc)
}
// CancelAllAfter cancels all orders after timeout
func (b *BTSE) CancelAllAfter(timeout int) error {
req := make(map[string]interface{})
req["timeout"] = timeout
return b.SendAuthenticatedHTTPRequest(http.MethodPost, btseCancelAllAfter, true, url.Values{}, req, nil, orderFunc)
}
// IndexOrderPeg create peg order that will track a certain percentage above/below the index price
func (b *BTSE) IndexOrderPeg(clOrderID string, deviation float64, postOnly bool, price float64, side string, size, stealth, stopPrice float64, symbol, timeInForce string, trailValue, triggerPrice float64, txType, orderType string) ([]Order, error) {
var o []Order
req := make(map[string]interface{})
if clOrderID != "" {
req["clOrderID"] = clOrderID
}
if deviation > 0.0 {
req["deviation"] = deviation
}
if postOnly {
req["postOnly"] = postOnly
}
if price > 0.0 {
req["price"] = price
}
if side != "" {
req["side"] = side
}
if size > 0.0 {
req["size"] = size
}
if stealth > 0.0 {
req["stealth"] = stealth
}
if stopPrice > 0.0 {
req["stopPrice"] = stopPrice
}
if symbol != "" {
req["symbol"] = symbol
}
if timeInForce != "" {
req["time_in_force"] = timeInForce
}
if trailValue > 0.0 {
req["trailValue"] = trailValue
}
if triggerPrice > 0.0 {
req["triggerPrice"] = triggerPrice
}
if txType != "" {
req["txType"] = txType
}
if orderType != "" {
req["type"] = orderType
}
return o, b.SendAuthenticatedHTTPRequest(http.MethodPost, btsePegOrder, true, url.Values{}, req, nil, orderFunc)
}
// TradeHistory returns previous trades on exchange
func (b *BTSE) TradeHistory(symbol string, start, end time.Time, beforeSerialID, afterSerialID, count int, includeOld bool, clOrderID, orderID string) (TradeHistory, error) {
var resp TradeHistory
urlValues := url.Values{}
if symbol != "" {
urlValues.Add("symbol", symbol)
}
if !start.IsZero() && !end.IsZero() {
if start.After(end) || end.Before(start) {
return resp, errors.New("start and end must both be valid")
}
urlValues.Add("start", strconv.FormatInt(start.Unix(), 10))
urlValues.Add("end", strconv.FormatInt(end.Unix(), 10))
}
if beforeSerialID > 0 {
urlValues.Add("beforeSerialId", strconv.Itoa(beforeSerialID))
}
if afterSerialID > 0 {
urlValues.Add("afterSerialId", strconv.Itoa(afterSerialID))
}
if includeOld {
urlValues.Add("includeOld", "true")
}
if count > 0 {
urlValues.Add("count", strconv.Itoa(count))
}
if clOrderID != "" {
urlValues.Add("clOrderId", clOrderID)
}
if orderID != "" {
urlValues.Add("orderID", orderID)
}
return resp, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseExchangeHistory, true, urlValues, nil, &resp, queryFunc)
}
// SendHTTPRequest sends an HTTP request to the desired endpoint
func (b *BTSE) SendHTTPRequest(method, endpoint string, result interface{}, spotEndpoint bool, f request.EndpointLimit) error {
p := btseSPOTPath + btseSPOTAPIPath
if !spotEndpoint {
p = btseFuturesPath + btseFuturesAPIPath
}
return b.SendPayload(context.Background(), &request.Item{
Method: method,
Path: b.API.Endpoints.URL + p + endpoint,
Result: result,
Verbose: b.Verbose,
HTTPDebugging: b.HTTPDebugging,
HTTPRecording: b.HTTPRecording,
Endpoint: f,
})
}
// SendAuthenticatedHTTPRequest sends an authenticated HTTP request to the desired endpoint
func (b *BTSE) SendAuthenticatedHTTPRequest(method, endpoint string, isSpot bool, values url.Values, req map[string]interface{}, result interface{}, f request.EndpointLimit) error {
if !b.AllowAuthenticatedRequest() {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
b.Name)
}
// The concatenation is done this way because BTSE expect endpoint+nonce or endpoint+nonce+body
// when signing the data but the full path of the request is /spot/api/v3.2/<endpoint>
// its messy but it works and supports futures as well
host := b.API.Endpoints.URL
if isSpot {
host += btseSPOTPath + btseSPOTAPIPath + endpoint
endpoint = btseSPOTAPIPath + endpoint
} else {
host += btseFuturesPath + btseFuturesAPIPath
endpoint += btseFuturesAPIPath
}
var hmac []byte
var body io.Reader
nonce := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
headers := map[string]string{
"btse-api": b.API.Credentials.Key,
"btse-nonce": nonce,
}
if req != nil {
reqPayload, err := json.Marshal(req)
if err != nil {
return err
}
body = bytes.NewBuffer(reqPayload)
hmac = crypto.GetHMAC(
crypto.HashSHA512_384,
[]byte((endpoint + nonce + string(reqPayload))),
[]byte(b.API.Credentials.Secret),
)
headers["Content-Type"] = "application/json"
} else {
hmac = crypto.GetHMAC(
crypto.HashSHA512_384,
[]byte((endpoint + nonce)),
[]byte(b.API.Credentials.Secret),
)
if len(values) > 0 {
host += "?" + values.Encode()
}
}
headers["btse-sign"] = crypto.HexEncodeToString(hmac)
if b.Verbose {
log.Debugf(log.ExchangeSys,
"%s Sending %s request to URL %s",
b.Name, method, endpoint)
}
return b.SendPayload(context.Background(), &request.Item{
Method: method,
Path: host,
Headers: headers,
Body: body,
Result: result,
AuthRequest: true,
Verbose: b.Verbose,
HTTPDebugging: b.HTTPDebugging,
HTTPRecording: b.HTTPRecording,
Endpoint: f,
})
}
// GetFee returns an estimate of fee based on type of transaction
func (b *BTSE) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
var fee float64
switch feeBuilder.FeeType {
case exchange.CryptocurrencyTradeFee:
fee = b.calculateTradingFee(feeBuilder) * feeBuilder.Amount * feeBuilder.PurchasePrice
case exchange.CryptocurrencyWithdrawalFee:
switch feeBuilder.Pair.Base {
case currency.USDT:
fee = 1.08
case currency.TUSD:
fee = 1.09
case currency.BTC:
fee = 0.0005
case currency.ETH:
fee = 0.01
case currency.LTC:
fee = 0.001
}
case exchange.InternationalBankDepositFee:
fee = getInternationalBankDepositFee(feeBuilder.Amount)
case exchange.InternationalBankWithdrawalFee:
fee = getInternationalBankWithdrawalFee(feeBuilder.Amount)
case exchange.OfflineTradeFee:
fee = getOfflineTradeFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
}
return fee, nil
}
// getOfflineTradeFee calculates the worst case-scenario trading fee
func getOfflineTradeFee(price, amount float64) float64 {
return 0.001 * price * amount
}
// getInternationalBankDepositFee returns international deposit fee
// Only when the initial deposit amount is less than $1000 or equivalent,
// BTSE will charge a small fee (0.25% or $3 USD equivalent, whichever is greater).
// The small deposit fee is charged in whatever currency it comes in.
func getInternationalBankDepositFee(amount float64) float64 {
var fee float64
if amount <= 100 {
fee = amount * 0.0025
if fee < 3 {
return 3
}
}
return fee
}
// getInternationalBankWithdrawalFee returns international withdrawal fee
// 0.1% (min25 USD)
func getInternationalBankWithdrawalFee(amount float64) float64 {
fee := amount * 0.0009
if fee < 25 {
return 25
}
return fee
}
// calculateTradingFee return fee based on users current fee tier or default values
func (b *BTSE) calculateTradingFee(feeBuilder *exchange.FeeBuilder) float64 {
formattedPair, err := b.FormatExchangeCurrency(feeBuilder.Pair, asset.Spot)
if err != nil {
if feeBuilder.IsMaker {
return 0.001
}
return 0.002
}
feeTiers, err := b.GetFeeInformation(formattedPair.String())
if err != nil {
if feeBuilder.IsMaker {
return 0.001
}
return 0.002
}
if feeBuilder.IsMaker {
return feeTiers[0].MakerFee
}
return feeTiers[0].TakerFee
}
func parseOrderTime(timeStr string) (time.Time, error) {
return time.Parse(common.SimpleTimeFormat, timeStr)
}