Skip to content

Commit

Permalink
Update BTSE RESTful API to version 2 (thrasher-corp#349)
Browse files Browse the repository at this point in the history
Update BTSE RESTful API to version 2
  • Loading branch information
MadCozBadd authored and thrasher- committed Oct 25, 2019
1 parent 8a0c5f9 commit f60051a
Show file tree
Hide file tree
Showing 5 changed files with 486 additions and 402 deletions.
187 changes: 109 additions & 78 deletions exchanges/btse/btse.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package btse

import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"

"github.com/thrasher-corp/gocryptotrader/common"
Expand All @@ -25,22 +26,23 @@ type BTSE struct {
}

const (
btseAPIURL = "https://api.btse.com/v1/restapi"
btseAPIVersion = "1"
btseAPIURL = "https://api.btse.com"
btseAPIPath = "/spot/v2/"

// Public endpoints
btseMarkets = "markets"
btseTrades = "trades"
btseTicker = "ticker"
btseStats = "stats"
btseTime = "time"
btseMarketOverview = "market_summary"
btseMarkets = "markets"
btseOrderbook = "orderbook"
btseTrades = "trades"
btseTicker = "ticker"
btseStats = "stats"
btseTime = "time"

// Authenticated endpoints
btseAccount = "account"
btseOrder = "order"
btsePendingOrders = "pending"
btseDeleteOrder = "deleteOrder"
btseDeleteOrders = "deleteOrders"
btseFills = "fills"
)

Expand Down Expand Up @@ -140,17 +142,30 @@ func (b *BTSE) Setup(exch *config.ExchangeConfig) {
}
}

// GetMarketsSummary stores market summary data
func (b *BTSE) GetMarketsSummary() (*HighLevelMarketData, error) {
var m HighLevelMarketData
return &m, b.SendHTTPRequest(http.MethodGet, btseMarketOverview, &m)
}

// GetMarkets returns a list of markets available on BTSE
func (b *BTSE) GetMarkets() (*Markets, error) {
var m Markets
return &m, b.SendHTTPRequest(http.MethodGet, btseMarkets, &m)
func (b *BTSE) GetMarkets() ([]Market, error) {
var m []Market
return m, b.SendHTTPRequest(http.MethodGet, btseMarkets, &m)
}

// FetchOrderBook gets orderbook data for a given pair
func (b *BTSE) FetchOrderBook(symbol string) (*Orderbook, error) {
var o Orderbook
endpoint := fmt.Sprintf("%s/%s", btseOrderbook, symbol)
return &o, b.SendHTTPRequest(http.MethodGet, endpoint, &o)
}

// GetTrades returns a list of trades for the specified symbol
func (b *BTSE) GetTrades(symbol string) (*Trades, error) {
var t Trades
func (b *BTSE) GetTrades(symbol string) ([]Trade, error) {
var t []Trade
endpoint := fmt.Sprintf("%s/%s", btseTrades, symbol)
return &t, b.SendHTTPRequest(http.MethodGet, endpoint, &t)
return t, b.SendHTTPRequest(http.MethodGet, endpoint, &t)

}

Expand Down Expand Up @@ -179,24 +194,28 @@ func (b *BTSE) GetServerTime() (*ServerTime, error) {
}

// GetAccountBalance returns the users account balance
func (b *BTSE) GetAccountBalance() (*AccountBalance, error) {
var a AccountBalance
return &a, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseAccount, nil, &a)
func (b *BTSE) GetAccountBalance() ([]CurrencyBalance, error) {
var a []CurrencyBalance
return a, b.SendAuthenticatedHTTPRequest(http.MethodGet, btseAccount, nil, &a)
}

// CreateOrder creates an order
func (b *BTSE) CreateOrder(amount, price float64, side, orderType, symbol, timeInForce, tag string) (*string, error) {
req := make(map[string]interface{})
req["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
req["price"] = strconv.FormatFloat(price, 'f', -1, 64)
req["side"] = side
req["type"] = orderType
req["product_id"] = symbol

req["amount"] = amount
req["price"] = price
if side != "" {
req["side"] = side
}
if orderType != "" {
req["type"] = orderType
}
if symbol != "" {
req["symbol"] = symbol
}
if timeInForce != "" {
req["time_in_force"] = timeInForce
req["timeInForce"] = timeInForce
}

if tag != "" {
req["tag"] = tag
}
Expand All @@ -210,51 +229,39 @@ func (b *BTSE) CreateOrder(amount, price float64, side, orderType, symbol, timeI
}

// GetOrders returns all pending orders
func (b *BTSE) GetOrders(productID string) (*OpenOrders, error) {
func (b *BTSE) GetOrders(symbol string) ([]OpenOrder, error) {
req := make(map[string]interface{})
if productID != "" {
req["product_id"] = productID
if symbol != "" {
req["symbol"] = symbol
}
var o OpenOrders
return &o, b.SendAuthenticatedHTTPRequest(http.MethodGet, btsePendingOrders, req, &o)
var o []OpenOrder
return o, b.SendAuthenticatedHTTPRequest(http.MethodGet, btsePendingOrders, req, &o)
}

// CancelExistingOrder cancels an order
func (b *BTSE) CancelExistingOrder(orderID, productID string) (*CancelOrder, error) {
func (b *BTSE) CancelExistingOrder(orderID, symbol string) (*CancelOrder, error) {
var c CancelOrder
req := make(map[string]interface{})
req["order_id"] = orderID
req["product_id"] = productID
req["symbol"] = symbol
return &c, b.SendAuthenticatedHTTPRequest(http.MethodPost, btseDeleteOrder, req, &c)
}

// CancelOrders cancels all orders
// productID optional. If product ID is sent, all orders of that specified market
// will be cancelled. If not specified, all orders of all markets will be cancelled
func (b *BTSE) CancelOrders(productID string) (*CancelOrder, error) {
var c CancelOrder
req := make(map[string]interface{})
if productID != "" {
req["product_id"] = productID
}
return &c, b.SendAuthenticatedHTTPRequest(http.MethodPost, btseDeleteOrders, req, &c)
}

// GetFills gets all filled orders
func (b *BTSE) GetFills(orderID, productID, before, after, limit string) (*FilledOrders, error) {
if orderID != "" && productID != "" {
return nil, errors.New("orderID and productID cannot co-exist in the same query")
} else if orderID == "" && productID == "" {
return nil, errors.New("orderID OR productID must be set")
func (b *BTSE) GetFills(orderID, symbol, before, after, limit, username string) ([]FilledOrder, error) {
if orderID != "" && symbol != "" {
return nil, errors.New("orderID and symbol cannot co-exist in the same query")
} else if orderID == "" && symbol == "" {
return nil, errors.New("orderID OR symbol must be set")
}

req := make(map[string]interface{})
if orderID != "" {
req["order_id"] = orderID
}

if productID != "" {
req["product_id"] = productID
if symbol != "" {
req["symbol"] = symbol
}

if before != "" {
Expand All @@ -268,15 +275,18 @@ func (b *BTSE) GetFills(orderID, productID, before, after, limit string) (*Fille
if limit != "" {
req["limit"] = limit
}
if username != "" {
req["username"] = username
}

var o FilledOrders
return &o, b.SendAuthenticatedHTTPRequest(http.MethodPost, btseFills, req, &o)
var o []FilledOrder
return o, b.SendAuthenticatedHTTPRequest(http.MethodPost, btseFills, req, &o)
}

// SendHTTPRequest sends an HTTP request to the desired endpoint
func (b *BTSE) SendHTTPRequest(method, endpoint string, result interface{}) error {
return b.SendPayload(method,
fmt.Sprintf("%s/%s", btseAPIURL, endpoint),
btseAPIURL+btseAPIPath+endpoint,
nil,
nil,
&result,
Expand All @@ -292,27 +302,41 @@ func (b *BTSE) SendAuthenticatedHTTPRequest(method, endpoint string, req map[str
if !b.AuthenticatedAPISupport {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, b.Name)
}

payload, err := common.JSONEncode(req)
if err != nil {
return errors.New("sendAuthenticatedAPIRequest: unable to JSON request")
}

path := btseAPIPath + endpoint
headers := make(map[string]string)
headers["API-KEY"] = b.APIKey
headers["API-PASSPHRASE"] = b.APISecret
if len(payload) > 0 {
headers["Content-Type"] = "application/json"
headers["btse-api"] = b.APIKey
nonce := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
headers["btse-nonce"] = nonce
var body io.Reader
var hmac []byte
var payload []byte
if len(req) != 0 {
var err error
payload, err = common.JSONEncode(req)
if err != nil {
return err
}
body = bytes.NewBuffer(payload)
hmac = common.GetHMAC(
common.HashSHA512_384,
[]byte((path + nonce + string(payload))),
[]byte(b.APISecret),
)
} else {
hmac = common.GetHMAC(
common.HashSHA512_384,
[]byte((path + nonce)),
[]byte(b.APISecret),
)
}

p := fmt.Sprintf("%s/%s", btseAPIURL, endpoint)
headers["btse-sign"] = common.HexEncodeToString(hmac)
if b.Verbose {
log.Debugf("Sending %s request to URL %s with params %s\n", method, p, string(payload))
log.Debugf("Sending %s request to URL %s with params %s\n", method, path, string(payload))
}
return b.SendPayload(method,
p,
btseAPIURL+path,
headers,
strings.NewReader(string(payload)),
body,
&result,
true,
false,
Expand All @@ -327,12 +351,19 @@ func (b *BTSE) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {

switch feeBuilder.FeeType {
case exchange.CryptocurrencyTradeFee:
fee = calculateTradingFee(feeBuilder.IsMaker)
fee = calculateTradingFee(feeBuilder.IsMaker) * feeBuilder.Amount * feeBuilder.PurchasePrice
case exchange.CryptocurrencyWithdrawalFee:
if feeBuilder.Pair.Base.Match(currency.BTC) {
switch feeBuilder.Pair.Base {
case currency.USDT:
fee = 1.08
case currency.TUSD:
fee = 1.09
case currency.BTC:
fee = 0.0005
} else if feeBuilder.Pair.Base.Match(currency.USDT) {
fee = 5
case currency.ETH:
fee = 0.01
case currency.LTC:
fee = 0.001
}
case exchange.InternationalBankDepositFee:
fee = getInternationalBankDepositFee(feeBuilder.Amount)
Expand All @@ -346,7 +377,7 @@ func (b *BTSE) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {

// getOfflineTradeFee calculates the worst case-scenario trading fee
func getOfflineTradeFee(price, amount float64) float64 {
return 0.0015 * price * amount
return 0.001 * price * amount
}

// getInternationalBankDepositFee returns international deposit fee
Expand All @@ -355,7 +386,7 @@ func getOfflineTradeFee(price, amount float64) float64 {
// The small deposit fee is charged in whatever currency it comes in.
func getInternationalBankDepositFee(amount float64) float64 {
var fee float64
if amount <= 1000 {
if amount <= 100 {
fee = amount * 0.0025
if fee < 3 {
return 3
Expand All @@ -367,7 +398,7 @@ func getInternationalBankDepositFee(amount float64) float64 {
// getInternationalBankWithdrawalFee returns international withdrawal fee
// 0.1% (min25 USD)
func getInternationalBankWithdrawalFee(amount float64) float64 {
fee := amount * 0.001
fee := amount * 0.0009

if fee < 25 {
return 25
Expand All @@ -380,7 +411,7 @@ func getInternationalBankWithdrawalFee(amount float64) float64 {
func calculateTradingFee(isMaker bool) float64 {
fee := 0.00050
if !isMaker {
fee = 0.0015
fee = 0.001
}
return fee
}
Expand Down
Loading

0 comments on commit f60051a

Please sign in to comment.