mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-06-04 23:16:54 +00:00
* Initial changes, removing exchange name as an arg and puts it in the pointer struct. Adds case to ws routines * Adds CancelAllOrders func, adds GetByExchangeAndID. Adds modify handler in routines.go * initial poor attempts to have bitmex work with new datahandler handlers. fixes ordersides * bitmex Completes new order * Better bitmex handling, but not complete. Begins a gargantuan task of unifying order data structs. Sometimes an order update will contain lot's of information, so its best to be able to update all fields of our orders, rather than just an arbitrary subset. As a result, everything will be broken for the foreseeable future :glitch_crab: * Removes old order handler which did nothing. Updates order properties for everything everywhere - now consistent. Changes order status. Adds asset type and wallet address to all order types * Adds order updater to update only relevant fields since the object is generic, we don't know what fields are passed from what exchanges. Adds "lastupdated" field to order.Detail. Expands order cancellation for engine orders. * Ensures that new orders are added to the ordermanager's order store. Saaa many comments. Internalises orderStore get func. Adds internalOrderID to orderdetail and adds websocket support for it * Fixes a cancelAllOrders oopsie doopsie * Adds potential func to update orderdetails from an orderdetail struct. Unsure if will keep. * Begins btcmarkets implementation. Expands order "stringToOrder" funcs to allow for some more flexible string coversions. Removes order.Submit via websocket as it would cause unlimited order place issues :D * Finishes btc markets without testing * Adds untested ws auth func to btse * Finises btse, fixes btcmarkets bug * Adds coinbasepro support * Fixes a few more fields in coinbase pro and readds the extra subs * Begins work on coinbene. Plus theyve added a new ws connection yeee * Wasted a bunch of time adding support to an additional websocket that isn't needed ;_; Fixed a bug in coinbasepro. Fully kitted out coinbene support. Updates order types with all fields * Removes extra websocket connection ;_; * Finishes gemini. Fixes order side unknown * Adds okgroup support. Moves byte reading to another function to allow for unit testing. Updates routines to use pointers. Updates date update handling for order details * Finishes order data for okgroup websocket, but starts the STRANGE process of converting all other websocket endpoints to be a little less silly * Cleans up okroup websocket implementation. Fixes bug in Gemini * Adds poloniex support. Updates ws order handling * new bitmex support. Adds some tests now that its all in its own func. Fixes poloniex bug * Begins work on authenticated binance websocket * Attempts to track user data via binance websocket * Maybe finishes Binance websocket support * Begins adding test coverage to orders.go. Updates names of script properties to match updated * Begins an experiment with code coverage. Fixes more rebase issues * Completes orders coverage. Botches a few other things though. Fixes more scripting stuff * All tests in engine package pass * Adds some loevely routine tests * Moves ordermanager to test Bot ordermanager Adds lovely routine tests to ensure things that get sent to be handled the data handler are handled by the data handler by handling them * Replaces "wsHandleData" with "wsReadData" as that's what its going to do now. * Splits all wsHandleData into wsReadData and wsHandleData to allow for easy testing via sending []byte json examples to test proper functionality. Breaks so many tests * Fixes majority of test issues. But data races which are tough on the engine package * "Fixes" test by removing shutdown test. It interferes with too many things. Requires some thought * Tests all the binance websocket points * Adds better bitfinex websocket support. * Adds testing for bitfinex, bitstamp and btcmarkets. Fixes websocket bugs encountered * Adds BTSE ws tests. Fixes bugs in ws * Adds coinbase pro tests. Fixes any issues * Coinbene tests * Starts to handle coinut. Runs into a problem conceptually regarding websocket roundtrip and orders. Both events need to happen without impacting eachother/racing * Addresses a data race issue regarding websocket and bot order management submission - order submission locks at an earlier point to prevent routines.go from creating an order before order submission creates it. Updates rpcserver to use order management bot to submit orders. * Finishes the hectic coinut testing * Adds tests for gateio * Fixes rebase issues. Updates tests to work without being overloaded * Begins testing of gemini. fixes up minor issues * ginishes gemini tests and fixes * Adds hitbtc tests. Fixes all the many issues with hitbtc websocket * Adds remaining tests. Increases default test channel limit again * Begins work towards huobi tests * Finishes huobi tests * Fixed all mythical rebase adventures * Begins kraken transformation * Finishes kraken. Fixes coinbene leverage now that its changed * Begins okgroup testing * Adds okgroup ws tests * Does some poloniex * Fixes basic curreny issue by extracting to func * Begins redesign of poloniex websocket datahandling. Completes authenticated handling, now onto unauth * Finishes poloniex revision * Finishes ZB additions * Fixes data races * Fixes rebase issues. Fixes bad kraken logic * Fixes after reviewing code * lint everywhere * Fixes lingering lints * lint * Adds test coverage to order detail and modify updating * Fixes linting * Fixes huge int, fixes date tests * Adds GetByExchange, adds test for it. Protects fakepass echange. Renames DisplayQty to DisplayQuantity. Removes verbose. Adds some websocket properties. Updates bitmex asset type in test * Addresses timestamps, type abbreviations, verbosity. Expands binance kline switch cases. Updates some websocket capabilities. * Adds coverage to the stringToOrderType/Status functions introduced in PR * Minor fixes addressing some time, error text and use of StringDataCompareInsensitive * Introduces shiny new system which checks if there is an awaiting ID, if found, processes via wrapper method, else, goes through wsHandleData method. Removes weird locking system from wrapper/websocket data race. Updates bitfinex to properly handle websocket order requests and notifications * Moves fakePassingExchange to test_helper. Fixes some order side implementations for trades. Botches a new error type * Adds new error type to track and handle order classification errors separately * Fully fleshes out ClassificationError for all instances of status conversion. Even in order trades and some wrapper functions * Introduces common.SimpleTimeFormat for "2006-01-02 15:04:05". Fixes binance and bitfinex issues with auth endpoint use, map casting. Expands more order.ClassificationError usage. Fixes some more generic websocket response errors * Future proofs order updating by utilising asset types. Expands testing to accomodate. Adds shiny new time type. Expands wrapper websocket functionality definitions * minty linty * Broken end of day code addressing basic nits on comments, returns and currency conversion * Adds testing to btcmarkets websocket. Also updates websocket orderbook to use update instead * Fixes fun rebase fun fun so fun * Addresses minor nits regarding changed interface and comments * Creates new function `GetRequestFormattedPairAndAssetType` to retrieve a currency pair and asset type based on a string. It will iterate over enabled pairs and compare them to formatted pairs and then return that pair if found. * Fixes test * Adds a single line to the end of the file, because that would be really bad if it wasn't there * Updates fakepassexchange to not use params, updates test params, uses fatal in some tests where its important, updates order manager to have a rwmutex, removes some returns, improves ws key test for binance, updates properties to reflect their actual values, adds some more websocket properties * Addresses binance switch linting * Updates leverage property to int64 * Fixes what was broken
837 lines
24 KiB
Go
837 lines
24 KiB
Go
package btcmarkets
|
|
|
|
import (
|
|
"bytes"
|
|
"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/request"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/websocket/wshandler"
|
|
)
|
|
|
|
const (
|
|
btcMarketsAPIURL = "https://api.btcmarkets.net"
|
|
btcMarketsAPIVersion = "/v3"
|
|
|
|
// UnAuthenticated EPs
|
|
btcMarketsAllMarkets = "/markets/"
|
|
btcMarketsGetTicker = "/ticker/"
|
|
btcMarketsGetTrades = "/trades?"
|
|
btcMarketOrderBooks = "/orderbook?"
|
|
btcMarketsCandles = "/candles?"
|
|
btcMarketsTickers = "tickers?"
|
|
btcMarketsMultipleOrderbooks = "/orderbooks?"
|
|
btcMarketsGetTime = "/time"
|
|
btcMarketsWithdrawalFees = "/withdrawal-fees"
|
|
btcMarketsUnauthPath = btcMarketsAPIURL + btcMarketsAPIVersion + btcMarketsAllMarkets
|
|
|
|
// Authenticated EPs
|
|
btcMarketsAccountBalance = "/accounts/me/balances"
|
|
btcMarketsTradingFees = "/accounts/me/trading-fees"
|
|
btcMarketsTransactions = "/accounts/me/transactions"
|
|
btcMarketsOrders = "/orders"
|
|
btcMarketsTradeHistory = "/trades"
|
|
btcMarketsWithdrawals = "/withdrawals"
|
|
btcMarketsDeposits = "/deposits"
|
|
btcMarketsTransfers = "/transfers"
|
|
btcMarketsAddresses = "/addresses"
|
|
btcMarketsAssets = "/assets"
|
|
btcMarketsReports = "/reports"
|
|
btcMarketsBatchOrders = "/batchorders"
|
|
|
|
orderFailed = "Failed"
|
|
orderPartiallyCancelled = "Partially Cancelled"
|
|
orderCancelled = "Cancelled"
|
|
orderFullyMatched = "Fully Matched"
|
|
orderPartiallyMatched = "Partially Matched"
|
|
orderPlaced = "Placed"
|
|
orderAccepted = "Accepted"
|
|
|
|
ask = "ask"
|
|
limit = "Limit"
|
|
market = "Market"
|
|
stopLimit = "Stop Limit"
|
|
stop = "Stop"
|
|
takeProfit = "Take Profit"
|
|
|
|
subscribe = "subscribe"
|
|
fundChange = "fundChange"
|
|
orderChange = "orderChange"
|
|
heartbeat = "heartbeat"
|
|
tick = "tick"
|
|
wsOB = "orderbookUpdate"
|
|
trade = "trade"
|
|
)
|
|
|
|
// BTCMarkets is the overarching type across the BTCMarkets package
|
|
type BTCMarkets struct {
|
|
exchange.Base
|
|
WebsocketConn *wshandler.WebsocketConnection
|
|
}
|
|
|
|
// GetHistoricCandles returns rangesize number of candles for the given granularity and pair starting from the latest available
|
|
func (b *BTCMarkets) GetHistoricCandles(pair currency.Pair, rangesize, granularity int64) ([]exchange.Candle, error) {
|
|
return nil, common.ErrNotYetImplemented
|
|
}
|
|
|
|
// GetMarkets returns the BTCMarkets instruments
|
|
func (b *BTCMarkets) GetMarkets() ([]Market, error) {
|
|
var resp []Market
|
|
return resp, b.SendHTTPRequest(btcMarketsUnauthPath, &resp)
|
|
}
|
|
|
|
// GetTicker returns a ticker
|
|
// symbol - example "btc" or "ltc"
|
|
func (b *BTCMarkets) GetTicker(marketID string) (Ticker, error) {
|
|
var tick Ticker
|
|
return tick, b.SendHTTPRequest(btcMarketsUnauthPath+marketID+btcMarketsGetTicker, &tick)
|
|
}
|
|
|
|
// GetTrades returns executed trades on the exchange
|
|
func (b *BTCMarkets) GetTrades(marketID string, before, after, limit int64) ([]Trade, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var trades []Trade
|
|
params := url.Values{}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return trades, b.SendHTTPRequest(btcMarketsUnauthPath+marketID+btcMarketsGetTrades+params.Encode(),
|
|
&trades)
|
|
}
|
|
|
|
// GetOrderbook returns current orderbook
|
|
func (b *BTCMarkets) GetOrderbook(marketID string, level int64) (Orderbook, error) {
|
|
var orderbook Orderbook
|
|
var temp tempOrderbook
|
|
params := url.Values{}
|
|
if level != 0 {
|
|
params.Set("level", strconv.FormatInt(level, 10))
|
|
}
|
|
err := b.SendHTTPRequest(btcMarketsUnauthPath+marketID+btcMarketOrderBooks+params.Encode(),
|
|
&temp)
|
|
if err != nil {
|
|
return orderbook, err
|
|
}
|
|
|
|
orderbook.MarketID = temp.MarketID
|
|
orderbook.SnapshotID = temp.SnapshotID
|
|
for x := range temp.Asks {
|
|
price, err := strconv.ParseFloat(temp.Asks[x][0], 64)
|
|
if err != nil {
|
|
return orderbook, err
|
|
}
|
|
amount, err := strconv.ParseFloat(temp.Asks[x][1], 64)
|
|
if err != nil {
|
|
return orderbook, err
|
|
}
|
|
orderbook.Asks = append(orderbook.Asks, OBData{
|
|
Price: price,
|
|
Volume: amount,
|
|
})
|
|
}
|
|
for a := range temp.Bids {
|
|
price, err := strconv.ParseFloat(temp.Bids[a][0], 64)
|
|
if err != nil {
|
|
return orderbook, err
|
|
}
|
|
amount, err := strconv.ParseFloat(temp.Bids[a][1], 64)
|
|
if err != nil {
|
|
return orderbook, err
|
|
}
|
|
orderbook.Bids = append(orderbook.Bids, OBData{
|
|
Price: price,
|
|
Volume: amount,
|
|
})
|
|
}
|
|
return orderbook, nil
|
|
}
|
|
|
|
// GetMarketCandles gets candles for specified currency pair
|
|
func (b *BTCMarkets) GetMarketCandles(marketID, timeWindow, from, to string, before, after, limit int64) ([]MarketCandle, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var marketCandles []MarketCandle
|
|
var temp [][]string
|
|
params := url.Values{}
|
|
if timeWindow != "" {
|
|
params.Set("timeWindow", timeWindow)
|
|
}
|
|
if from != "" {
|
|
params.Set("from", from)
|
|
}
|
|
if to != "" {
|
|
params.Set("to", to)
|
|
}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
err := b.SendHTTPRequest(btcMarketsUnauthPath+marketID+btcMarketsCandles+params.Encode(),
|
|
&temp)
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
var tempData MarketCandle
|
|
var tempTime time.Time
|
|
for x := range temp {
|
|
tempTime, err = time.Parse(time.RFC3339, temp[x][0])
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
tempData.Time = tempTime
|
|
tempData.Open, err = strconv.ParseFloat(temp[x][1], 64)
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
tempData.High, err = strconv.ParseFloat(temp[x][2], 64)
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
tempData.Low, err = strconv.ParseFloat(temp[x][3], 64)
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
tempData.Close, err = strconv.ParseFloat(temp[x][4], 64)
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
tempData.Volume, err = strconv.ParseFloat(temp[x][5], 64)
|
|
if err != nil {
|
|
return marketCandles, err
|
|
}
|
|
marketCandles = append(marketCandles, tempData)
|
|
}
|
|
return marketCandles, nil
|
|
}
|
|
|
|
// GetTickers gets multiple tickers
|
|
func (b *BTCMarkets) GetTickers(marketIDs []currency.Pair) ([]Ticker, error) {
|
|
var tickers []Ticker
|
|
params := url.Values{}
|
|
for x := range marketIDs {
|
|
params.Add("marketId", marketIDs[x].String())
|
|
}
|
|
return tickers, b.SendHTTPRequest(btcMarketsUnauthPath+btcMarketsTickers+params.Encode(),
|
|
&tickers)
|
|
}
|
|
|
|
// GetMultipleOrderbooks gets orderbooks
|
|
func (b *BTCMarkets) GetMultipleOrderbooks(marketIDs []string) ([]Orderbook, error) {
|
|
var orderbooks []Orderbook
|
|
var temp []tempOrderbook
|
|
var tempOB Orderbook
|
|
params := url.Values{}
|
|
for x := range marketIDs {
|
|
params.Add("marketId", marketIDs[x])
|
|
}
|
|
err := b.SendHTTPRequest(btcMarketsUnauthPath+btcMarketsMultipleOrderbooks+params.Encode(),
|
|
&temp)
|
|
if err != nil {
|
|
return orderbooks, err
|
|
}
|
|
for i := range temp {
|
|
var price, volume float64
|
|
tempOB.MarketID = temp[i].MarketID
|
|
tempOB.SnapshotID = temp[i].SnapshotID
|
|
for a := range temp[i].Asks {
|
|
volume, err = strconv.ParseFloat(temp[i].Asks[a][1], 64)
|
|
if err != nil {
|
|
return orderbooks, err
|
|
}
|
|
price, err = strconv.ParseFloat(temp[i].Asks[a][0], 64)
|
|
if err != nil {
|
|
return orderbooks, err
|
|
}
|
|
tempOB.Asks = append(tempOB.Asks, OBData{Price: price, Volume: volume})
|
|
}
|
|
for y := range temp[i].Bids {
|
|
volume, err = strconv.ParseFloat(temp[i].Bids[y][1], 64)
|
|
if err != nil {
|
|
return orderbooks, err
|
|
}
|
|
price, err = strconv.ParseFloat(temp[i].Bids[y][0], 64)
|
|
if err != nil {
|
|
return orderbooks, err
|
|
}
|
|
tempOB.Bids = append(tempOB.Bids, OBData{Price: price, Volume: volume})
|
|
}
|
|
orderbooks = append(orderbooks, tempOB)
|
|
}
|
|
return orderbooks, nil
|
|
}
|
|
|
|
// GetServerTime gets time from btcmarkets
|
|
func (b *BTCMarkets) GetServerTime() (time.Time, error) {
|
|
var resp TimeResp
|
|
return resp.Time, b.SendHTTPRequest(btcMarketsAPIURL+btcMarketsAPIVersion+btcMarketsGetTime,
|
|
&resp)
|
|
}
|
|
|
|
// GetAccountBalance returns the full account balance
|
|
func (b *BTCMarkets) GetAccountBalance() ([]AccountData, error) {
|
|
var resp []AccountData
|
|
return resp,
|
|
b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsAccountBalance,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetTradingFees returns trading fees for all pairs based on trading activity
|
|
func (b *BTCMarkets) GetTradingFees() (TradingFeeResponse, error) {
|
|
var resp TradingFeeResponse
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsTradingFees,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetTradeHistory returns trade history
|
|
func (b *BTCMarkets) GetTradeHistory(marketID, orderID string, before, after, limit int64) ([]TradeHistoryData, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var resp []TradeHistoryData
|
|
params := url.Values{}
|
|
if marketID != "" {
|
|
params.Set("marketId", marketID)
|
|
}
|
|
if orderID != "" {
|
|
params.Set("orderId", orderID)
|
|
}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsTradeHistory, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetTradeByID returns the singular trade of the ID given
|
|
func (b *BTCMarkets) GetTradeByID(id string) (TradeHistoryData, error) {
|
|
var resp TradeHistoryData
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsTradeHistory+"/"+id,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// NewOrder requests a new order and returns an ID
|
|
func (b *BTCMarkets) NewOrder(marketID string, price, amount float64, orderType, side string, triggerPrice,
|
|
targetAmount float64, timeInForce string, postOnly bool, selfTrade, clientOrderID string) (OrderData, error) {
|
|
var resp OrderData
|
|
req := make(map[string]interface{})
|
|
req["marketId"] = marketID
|
|
req["price"] = strconv.FormatFloat(price, 'f', -1, 64)
|
|
req["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
|
|
req["type"] = orderType
|
|
req["side"] = side
|
|
if orderType == stopLimit || orderType == takeProfit || orderType == stop {
|
|
req["triggerPrice"] = strconv.FormatFloat(triggerPrice, 'f', -1, 64)
|
|
}
|
|
if targetAmount > 0 {
|
|
req["targetAmount"] = strconv.FormatFloat(targetAmount, 'f', -1, 64)
|
|
}
|
|
if timeInForce != "" {
|
|
req["timeInForce"] = timeInForce
|
|
}
|
|
req["postOnly"] = postOnly
|
|
if selfTrade != "" {
|
|
req["selfTrade"] = selfTrade
|
|
}
|
|
if clientOrderID != "" {
|
|
req["clientOrderID"] = clientOrderID
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodPost,
|
|
btcMarketsOrders,
|
|
req,
|
|
&resp,
|
|
orderFunc)
|
|
}
|
|
|
|
// GetOrders returns current order information on the exchange
|
|
func (b *BTCMarkets) GetOrders(marketID string, before, after, limit int64, openOnly bool) ([]OrderData, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var resp []OrderData
|
|
params := url.Values{}
|
|
if marketID != "" {
|
|
params.Set("marketId", marketID)
|
|
}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
if openOnly {
|
|
params.Set("status", "open")
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsOrders, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// CancelAllOpenOrdersByPairs cancels all open orders unless pairs are specified
|
|
func (b *BTCMarkets) CancelAllOpenOrdersByPairs(marketIDs []string) ([]CancelOrderResp, error) {
|
|
var resp []CancelOrderResp
|
|
req := make(map[string]interface{})
|
|
if len(marketIDs) > 0 {
|
|
var strTemp strings.Builder
|
|
for x := range marketIDs {
|
|
strTemp.WriteString("marketId=" + marketIDs[x] + "&")
|
|
}
|
|
req["marketId"] = strTemp.String()[:strTemp.Len()-1]
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodDelete,
|
|
btcMarketsOrders,
|
|
req,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// FetchOrder finds order based on the provided id
|
|
func (b *BTCMarkets) FetchOrder(id string) (OrderData, error) {
|
|
var resp OrderData
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsOrders+"/"+id,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// RemoveOrder removes a given order
|
|
func (b *BTCMarkets) RemoveOrder(id string) (CancelOrderResp, error) {
|
|
var resp CancelOrderResp
|
|
return resp, b.SendAuthenticatedRequest(http.MethodDelete,
|
|
btcMarketsOrders+"/"+id,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// ListWithdrawals lists the withdrawal history
|
|
func (b *BTCMarkets) ListWithdrawals(before, after, limit int64) ([]TransferData, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var resp []TransferData
|
|
params := url.Values{}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsWithdrawals, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetWithdrawal gets withdrawawl info for a given id
|
|
func (b *BTCMarkets) GetWithdrawal(id string) (TransferData, error) {
|
|
var resp TransferData
|
|
if id == "" {
|
|
return resp, errors.New("id cannot be an empty string")
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsWithdrawals+"/"+id,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// ListDeposits lists the deposit history
|
|
func (b *BTCMarkets) ListDeposits(before, after, limit int64) ([]TransferData, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var resp []TransferData
|
|
params := url.Values{}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsDeposits, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetDeposit gets deposit info for a given ID
|
|
func (b *BTCMarkets) GetDeposit(id string) (TransferData, error) {
|
|
var resp TransferData
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsDeposits+"/"+id,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// ListTransfers lists the past asset transfers
|
|
func (b *BTCMarkets) ListTransfers(before, after, limit int64) ([]TransferData, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var resp []TransferData
|
|
params := url.Values{}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsTransfers, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetTransfer gets asset transfer info for a given ID
|
|
func (b *BTCMarkets) GetTransfer(id string) (TransferData, error) {
|
|
var resp TransferData
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsTransfers+"/"+id,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// FetchDepositAddress gets deposit address for the given asset
|
|
func (b *BTCMarkets) FetchDepositAddress(assetName string, before, after, limit int64) (DepositAddress, error) {
|
|
var resp DepositAddress
|
|
if (before > 0) && (after >= 0) {
|
|
return resp, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
params := url.Values{}
|
|
params.Set("assetName", assetName)
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsAddresses, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetWithdrawalFees gets withdrawal fees for all assets
|
|
func (b *BTCMarkets) GetWithdrawalFees() ([]WithdrawalFeeData, error) {
|
|
var resp []WithdrawalFeeData
|
|
return resp, b.SendHTTPRequest(btcMarketsAPIURL+btcMarketsAPIVersion+btcMarketsWithdrawalFees,
|
|
&resp)
|
|
}
|
|
|
|
// ListAssets lists all available assets
|
|
func (b *BTCMarkets) ListAssets() ([]AssetData, error) {
|
|
var resp []AssetData
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsAssets,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// GetTransactions gets trading fees
|
|
func (b *BTCMarkets) GetTransactions(assetName string, before, after, limit int64) ([]TransactionData, error) {
|
|
if (before > 0) && (after >= 0) {
|
|
return nil, errors.New("BTCMarkets only supports either before or after, not both")
|
|
}
|
|
var resp []TransactionData
|
|
params := url.Values{}
|
|
if assetName != "" {
|
|
params.Set("assetName", assetName)
|
|
}
|
|
if before > 0 {
|
|
params.Set("before", strconv.FormatInt(before, 10))
|
|
}
|
|
if after >= 0 {
|
|
params.Set("after", strconv.FormatInt(after, 10))
|
|
}
|
|
if limit > 0 {
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
common.EncodeURLValues(btcMarketsTransactions, params),
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// CreateNewReport creates a new report
|
|
func (b *BTCMarkets) CreateNewReport(reportType, format string) (CreateReportResp, error) {
|
|
var resp CreateReportResp
|
|
req := make(map[string]interface{})
|
|
req["type"] = reportType
|
|
req["format"] = format
|
|
return resp, b.SendAuthenticatedRequest(http.MethodPost,
|
|
btcMarketsReports,
|
|
req,
|
|
&resp,
|
|
newReportFunc)
|
|
}
|
|
|
|
// GetReport finds details bout a past report
|
|
func (b *BTCMarkets) GetReport(reportID string) (ReportData, error) {
|
|
var resp ReportData
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsReports+"/"+reportID,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// RequestWithdraw requests withdrawals
|
|
func (b *BTCMarkets) RequestWithdraw(assetName string, amount float64,
|
|
toAddress, accountName, accountNumber, bsbNumber, bankName string) (TransferData, error) {
|
|
var resp TransferData
|
|
req := make(map[string]interface{})
|
|
req["assetName"] = assetName
|
|
req["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
|
|
if assetName != "AUD" {
|
|
req["toAddress"] = toAddress
|
|
} else {
|
|
if accountName != "" {
|
|
req["accountName"] = accountName
|
|
}
|
|
if accountNumber != "" {
|
|
req["accountNumber"] = accountNumber
|
|
}
|
|
if bsbNumber != "" {
|
|
req["bsbNumber"] = bsbNumber
|
|
}
|
|
if bankName != "" {
|
|
req["bankName"] = bankName
|
|
}
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodPost,
|
|
btcMarketsWithdrawals,
|
|
req,
|
|
&resp,
|
|
withdrawFunc)
|
|
}
|
|
|
|
// BatchPlaceCancelOrders places and cancels batch orders
|
|
func (b *BTCMarkets) BatchPlaceCancelOrders(cancelOrders []CancelBatch, placeOrders []PlaceBatch) (BatchPlaceCancelResponse, error) {
|
|
var resp BatchPlaceCancelResponse
|
|
var orderRequests []interface{}
|
|
if len(cancelOrders)+len(placeOrders) > 4 {
|
|
return resp, errors.New("BTCMarkets can only handle 4 orders at a time")
|
|
}
|
|
for x := range cancelOrders {
|
|
orderRequests = append(orderRequests, CancelOrderMethod{CancelOrder: cancelOrders[x]})
|
|
}
|
|
for y := range placeOrders {
|
|
if placeOrders[y].ClientOrderID == "" {
|
|
return resp, errors.New("placeorders must have clientorderids filled")
|
|
}
|
|
orderRequests = append(orderRequests, PlaceOrderMethod{PlaceOrder: placeOrders[y]})
|
|
}
|
|
return resp, b.SendAuthenticatedRequest(http.MethodPost,
|
|
btcMarketsBatchOrders,
|
|
orderRequests,
|
|
&resp,
|
|
batchFunc)
|
|
}
|
|
|
|
// GetBatchTrades gets batch trades
|
|
func (b *BTCMarkets) GetBatchTrades(ids []string) (BatchTradeResponse, error) {
|
|
var resp BatchTradeResponse
|
|
if len(ids) > 50 {
|
|
return resp, errors.New("batchtrades can only handle 50 ids at a time")
|
|
}
|
|
marketIDs := strings.Join(ids, ",")
|
|
return resp, b.SendAuthenticatedRequest(http.MethodGet,
|
|
btcMarketsBatchOrders+"/"+marketIDs,
|
|
nil,
|
|
&resp,
|
|
request.Auth)
|
|
}
|
|
|
|
// CancelBatchOrders cancels given ids
|
|
func (b *BTCMarkets) CancelBatchOrders(ids []string) (BatchCancelResponse, error) {
|
|
var resp BatchCancelResponse
|
|
marketIDs := strings.Join(ids, ",")
|
|
return resp, b.SendAuthenticatedRequest(http.MethodDelete,
|
|
btcMarketsBatchOrders+"/"+marketIDs,
|
|
nil,
|
|
&resp,
|
|
batchFunc)
|
|
}
|
|
|
|
// SendHTTPRequest sends an unauthenticated HTTP request
|
|
func (b *BTCMarkets) SendHTTPRequest(path string, result interface{}) error {
|
|
return b.SendPayload(&request.Item{
|
|
Method: http.MethodGet,
|
|
Path: path,
|
|
Result: result,
|
|
Verbose: b.Verbose,
|
|
HTTPDebugging: b.HTTPDebugging,
|
|
HTTPRecording: b.HTTPRecording,
|
|
})
|
|
}
|
|
|
|
// SendAuthenticatedRequest sends an authenticated HTTP request
|
|
func (b *BTCMarkets) SendAuthenticatedRequest(method, path string, data, result interface{}, f request.EndpointLimit) (err error) {
|
|
if !b.AllowAuthenticatedRequest() {
|
|
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
|
|
b.Name)
|
|
}
|
|
|
|
strTime := strconv.FormatInt(time.Now().UTC().UnixNano()/1000000, 10)
|
|
|
|
var body io.Reader
|
|
var payload, hmac []byte
|
|
switch data.(type) {
|
|
case map[string]interface{}, []interface{}:
|
|
payload, err = json.Marshal(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
body = bytes.NewBuffer(payload)
|
|
strMsg := method + btcMarketsAPIVersion + path + strTime + string(payload)
|
|
hmac = crypto.GetHMAC(crypto.HashSHA512,
|
|
[]byte(strMsg), []byte(b.API.Credentials.Secret))
|
|
default:
|
|
strArray := strings.Split(path, "?")
|
|
hmac = crypto.GetHMAC(crypto.HashSHA512,
|
|
[]byte(method+btcMarketsAPIVersion+strArray[0]+strTime),
|
|
[]byte(b.API.Credentials.Secret))
|
|
}
|
|
|
|
headers := make(map[string]string)
|
|
headers["Accept"] = "application/json"
|
|
headers["Accept-Charset"] = "UTF-8"
|
|
headers["Content-Type"] = "application/json"
|
|
headers["BM-AUTH-APIKEY"] = b.API.Credentials.Key
|
|
headers["BM-AUTH-TIMESTAMP"] = strTime
|
|
headers["BM-AUTH-SIGNATURE"] = crypto.Base64Encode(hmac)
|
|
|
|
return b.SendPayload(&request.Item{
|
|
Method: method,
|
|
Path: btcMarketsAPIURL + btcMarketsAPIVersion + path,
|
|
Headers: headers,
|
|
Body: body,
|
|
Result: result,
|
|
AuthRequest: true,
|
|
NonceEnabled: false,
|
|
Verbose: b.Verbose,
|
|
HTTPDebugging: b.HTTPDebugging,
|
|
HTTPRecording: b.HTTPRecording,
|
|
Endpoint: f,
|
|
})
|
|
}
|
|
|
|
// GetFee returns an estimate of fee based on type of transaction
|
|
func (b *BTCMarkets) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
|
|
var fee float64
|
|
|
|
switch feeBuilder.FeeType {
|
|
case exchange.CryptocurrencyTradeFee:
|
|
temp, err := b.GetTradingFees()
|
|
if err != nil {
|
|
return fee, err
|
|
}
|
|
for x := range temp.FeeByMarkets {
|
|
if currency.NewPairFromString(temp.FeeByMarkets[x].MarketID) == feeBuilder.Pair {
|
|
fee = temp.FeeByMarkets[x].MakerFeeRate
|
|
if !feeBuilder.IsMaker {
|
|
fee = temp.FeeByMarkets[x].TakerFeeRate
|
|
}
|
|
}
|
|
}
|
|
case exchange.CryptocurrencyWithdrawalFee:
|
|
temp, err := b.GetWithdrawalFees()
|
|
if err != nil {
|
|
return fee, err
|
|
}
|
|
for x := range temp {
|
|
if currency.NewCode(temp[x].AssetName) == feeBuilder.Pair.Base {
|
|
fee = temp[x].Fee * feeBuilder.PurchasePrice * feeBuilder.Amount
|
|
}
|
|
}
|
|
case exchange.InternationalBankWithdrawalFee:
|
|
return 0, errors.New("international bank withdrawals are not supported")
|
|
|
|
case exchange.OfflineTradeFee:
|
|
fee = getOfflineTradeFee(feeBuilder)
|
|
}
|
|
if fee < 0 {
|
|
fee = 0
|
|
}
|
|
return fee, nil
|
|
}
|
|
|
|
// getOfflineTradeFee calculates the worst case-scenario trading fee
|
|
func getOfflineTradeFee(feeBuilder *exchange.FeeBuilder) float64 {
|
|
switch {
|
|
case feeBuilder.Pair.IsCryptoPair():
|
|
return 0.002 * feeBuilder.PurchasePrice * feeBuilder.Amount
|
|
default:
|
|
return 0.0085 * feeBuilder.PurchasePrice * feeBuilder.Amount
|
|
}
|
|
}
|