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

* WIP progress

* Finish initial currency string error returns

* fix whoopsie testing for non https insecureinos

* Current WIP for getEnabledPairs check and error return

* WIP continued

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

* More updates -WIP

* Wip continued including potential interface

* Current WIP

* pairs manager pass

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

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

* purge logger references after merge

* go mod tidy after merge

* Pointer change WIP

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

* WIP

* Clean

* Fix some linter issues

* Fix more linter issues

* even more linters

* xtda nits

* revert pointer change and rm field

* Addr madcozbadd nits

* fix linter issues: shadow declarations

* Fix linter issues: gocritic huge things

* linter issue fix

* Addr nits

* flush go mod files

* after merge woops

* fix shadow dec

* Addr thrasher nits

* addr nits

* fix some issues

* more fixes

* RM println

* Addr glorious nits

* Add helper method for setting assets

* add missing format directive

* Addr nits

* Actually process new futures contracts -_- derp

* WIP for GRPC upgrade for pair management

* update config pairs

* finished disabling and enabling asset

* linked update of tradable pairs to cli

* fix oopsies

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

* update template

* don't add disabled asset items to initial sync

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

* WIP on getting a channel to unsub

* Wip track down unsubscribe bug and start creating streaming interface

* purge websocket orderbook object and centralised updating routine for orderbook

* general clean before interface implementation

* stage one connection interface WIP

* WIP

* repackage wshandler WIP

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

* design change on mange subscription routine WIP

* integrated ZB with the new webosocket updates

* WIP - okex conversion

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

* integrate another range of exchanges for websocket update

* Added subscriber and unsubscriber methods to websocket functionality

* fixed tests WIP

* amalgamate cache setup with main websocket setup

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

* added in colon

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

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

* RM line

* bitstamp pass

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

* Batch outgoing subscriptions and fix unsubscribe bug

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

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

* Batch outgoing subs and unsubs

* Fixes bug when matching return from authentication

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

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

* Add error handling

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

* hitBTC pass

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

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

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

* RM debug output

* rm func to get shutdown channel

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

* okgroup WIP

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

* poloniex pass

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

* initial clean

* centralised request matching mechanism

* websocket main improvements WIP

* WIP

* Websocket management via gctcli WIP

* GRPC expansion

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

* Fix continuous spawning of routines bug on error with reconnection

* Addr linter issues

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

* fix linter issue

* fix woopsie

* End of day WIP

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

* fix gateio test and unsubscribe bug

* revert comment out code

* websocketAPI changed to to true in configtest.json

* fix race in gateio test

* End of day WIP for websocket tests.

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

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

* Added verbosity check for setting websocket URL

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

* purge dodgy coding

* Fix tests, drop blocking chan in websocket Dial function

* few more changes

* race condition fix for websocket tests.

* fix intermittent test failure due to underlying hash table storage

* Address madcuzbad nit

* RM superfluous printlines

* Add quick top example with paramater fields

* First pass Glorious nits

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

* addr madcozbadd nits

* as per glorious suggestion rm'd loadedJSON field

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

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

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

* as per glorious suggestion restructured return error for websocket

* addr glorious suggestions

* fix linter issues

* purge non-existent pair from testdata

* add side field to struct and parse

* addr glorious nits

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

* fix speeling mistwake

* Adds websocket functionality check before flushing websocket connection

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

* added websocket url check before setting with tests

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

* remove error return for func

* Continuation of tests

* continuation of tests

* Stop potential panic within pair creation function

* Implement changes to upstream

* rm sup comment

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

* fix test

* Fix linter issues

* Fix tests

* turn websocket off in config example

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

* Introduced err var for same error returns

* Add err var exchange base not found

* restructure function

* drop gctscript from generic response name

* drop managesub delay const as its not being used

* correctly implement websocket rate limiting for coinut

* remove quotations

* drop pair management check

* fix spelling

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

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

* update error description

* rm function

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

* append delimiter onto currency delimiter strings

* add test coverage

* rm functions as they are set as methods in base

* remove superfluous methods

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

* fix after rebase woopsie

* fix linter issues

* fix bug streamline code

* fix linter issues

* fix linter issues

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

* fix whoopsie

* fix websocket tests

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

* add test coverage

* add test coverage and verified futures pariing

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

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

* If asset enabled add pair and increase code coverage

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

* Add code coverage

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

* address glorious nits

* Addr xtda nits

* fix linter issues

* addr glorious nits

* xtda nits

* Addr glorious nits

* add subscription protection and removed a superfluous wait call

* fix test

* fix whoopsie

* addr xtda nits

* addr glorious nits

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

* consolidated rpc returned type and added in sucessful strings

* dropped stream timing down to 100ms

* DOC changes

* proxy and url usage string additions

* WIP

* go mod tidy rides again

* Addr nits

* Addr nits, fix tests

* fix wording

* add in test case for currency matching

* Add byte length check on outbound websocket payload subscriptions

* addr thrasher nits

* Addr madcozbadd nits

* addr linter issues

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

* fix futures account subscription bug

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

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

1186 lines
30 KiB
Go

package coinbene
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"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// Coinbene is the overarching type across this package
type Coinbene struct {
exchange.Base
}
const (
coinbeneAPIURL = "https://openapi-exchange.coinbene.com/api/exchange/"
coinbeneSwapAPIURL = "https://openapi-contract.coinbene.com/api/swap/"
coinbeneAuthPath = "/api/exchange/v2"
coinbeneSwapAuthPath = "/api/swap/v2"
coinbeneAPIVersion = "v2"
// Public endpoints
coinbeneGetTicker = "/market/ticker/one"
coinbeneGetTickersSpot = "/market/ticker/list"
coinbeneGetTickers = "/market/tickers"
coinbeneGetOrderBook = "/market/orderBook"
coinbeneGetKlines = "/market/klines"
// TODO: Implement function ---
coinbeneSpotKlines = "/market/instruments/candles"
coinbeneSpotExchangeRate = "/market/rate/list"
// ---
coinbeneGetTrades = "/market/trades"
coinbeneGetAllPairs = "/market/tradePair/list"
coinbenePairInfo = "/market/tradePair/one"
// Authenticated endpoints
coinbeneAccountInfo = "/account/info"
coinbeneGetUserBalance = "/account/list"
coinbeneAccountBalanceOne = "/account/one"
coinbenePlaceOrder = "/order/place"
coinbeneBatchPlaceOrder = "/order/batchPlaceOrder"
coinbeneTradeFills = "/order/trade/fills"
coinbeneOrderFills = "/order/fills"
coinbeneOrderInfo = "/order/info"
coinbeneCancelOrder = "/order/cancel"
coinbeneBatchCancel = "/order/batchCancel"
coinbeneOpenOrders = "/order/openOrders"
coinbeneOpenOrdersByPage = "/order/openOrdersByPage"
coinbeneClosedOrders = "/order/closedOrders"
coinbeneClosedOrdersByPage = "/order/closedOrdersByPage"
coinbeneListSwapPositions = "/position/list"
coinbenePositionFeeRate = "/position/feeRate"
limitOrder = "1"
marketOrder = "2"
postOnlyOrder = "8"
fillOrKillOrder = "9"
iosOrder = "10"
buyDirection = "1"
openLong = "openLong"
openShort = "openShort"
sellDirection = "2"
)
// GetAllPairs gets all pairs on the exchange
func (c *Coinbene) GetAllPairs() ([]PairData, error) {
resp := struct {
Data []PairData `json:"data"`
}{}
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneGetAllPairs
return resp.Data, c.SendHTTPRequest(path, spotPairs, &resp)
}
// GetPairInfo gets info about a single pair
func (c *Coinbene) GetPairInfo(symbol string) (PairData, error) {
resp := struct {
Data PairData `json:"data"`
}{}
params := url.Values{}
params.Set("symbol", symbol)
path := common.EncodeURLValues(c.API.Endpoints.URL+coinbeneAPIVersion+coinbenePairInfo, params)
return resp.Data, c.SendHTTPRequest(path, spotPairInfo, &resp)
}
// GetOrderbook gets and stores orderbook data for given pair
func (c *Coinbene) GetOrderbook(symbol string, size int64) (Orderbook, error) {
resp := struct {
Data struct {
Asks [][]string `json:"asks"`
Bids [][]string `json:"bids"`
Time time.Time `json:"timestamp"`
} `json:"data"`
}{}
params := url.Values{}
params.Set("symbol", symbol)
params.Set("depth", strconv.FormatInt(size, 10))
path := common.EncodeURLValues(c.API.Endpoints.URL+coinbeneAPIVersion+coinbeneGetOrderBook, params)
err := c.SendHTTPRequest(path, spotOrderbook, &resp)
if err != nil {
return Orderbook{}, err
}
processOB := func(ob [][]string) ([]OrderbookItem, error) {
var o []OrderbookItem
for x := range ob {
var price, amount float64
amount, err = strconv.ParseFloat(ob[x][1], 64)
if err != nil {
return nil, err
}
price, err = strconv.ParseFloat(ob[x][0], 64)
if err != nil {
return nil, err
}
o = append(o, OrderbookItem{
Price: price,
Amount: amount,
})
}
return o, nil
}
var s Orderbook
s.Bids, err = processOB(resp.Data.Bids)
if err != nil {
return s, err
}
s.Asks, err = processOB(resp.Data.Asks)
if err != nil {
return s, err
}
s.Time = resp.Data.Time
return s, nil
}
// GetTicker gets and stores ticker data for a currency pair
func (c *Coinbene) GetTicker(symbol string) (TickerData, error) {
resp := struct {
TickerData TickerData `json:"data"`
}{}
params := url.Values{}
params.Set("symbol", symbol)
path := common.EncodeURLValues(c.API.Endpoints.URL+coinbeneAPIVersion+coinbeneGetTicker, params)
return resp.TickerData, c.SendHTTPRequest(path, spotSpecificTicker, &resp)
}
// GetTickers gets and all spot tickers supported by the exchange
func (c *Coinbene) GetTickers() ([]TickerData, error) {
resp := struct {
TickerData []TickerData `json:"data"`
}{}
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneGetTickersSpot
return resp.TickerData, c.SendHTTPRequest(path, spotTickerList, &resp)
}
// GetTrades gets recent trades from the exchange
func (c *Coinbene) GetTrades(symbol string) (Trades, error) {
resp := struct {
Data [][]string `json:"data"`
}{}
params := url.Values{}
params.Set("symbol", symbol)
path := common.EncodeURLValues(c.API.Endpoints.URL+coinbeneAPIVersion+coinbeneGetTrades, params)
err := c.SendHTTPRequest(path, spotMarketTrades, &resp)
if err != nil {
return nil, err
}
var trades Trades
for x := range resp.Data {
tm, err := time.Parse(time.RFC3339, resp.Data[x][4])
if err != nil {
return nil, err
}
price, err := strconv.ParseFloat(resp.Data[x][1], 64)
if err != nil {
return nil, err
}
volume, err := strconv.ParseFloat(resp.Data[x][2], 64)
if err != nil {
return nil, err
}
trades = append(trades, TradeItem{
CurrencyPair: resp.Data[x][0],
Price: price,
Volume: volume,
Direction: resp.Data[x][3],
TradeTime: tm,
})
}
return trades, nil
}
// GetAccountBalances gets user balanace info
func (c *Coinbene) GetAccountBalances() ([]UserBalanceData, error) {
resp := struct {
Data []UserBalanceData `json:"data"`
}{}
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneGetUserBalance
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneGetUserBalance,
false,
nil,
&resp,
spotAccountInfo)
if err != nil {
return nil, err
}
return resp.Data, nil
}
// GetAccountAssetBalance gets user balanace info
func (c *Coinbene) GetAccountAssetBalance(symbol string) (UserBalanceData, error) {
v := url.Values{}
v.Set("asset", symbol)
resp := struct {
Data UserBalanceData `json:"data"`
}{}
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneAccountBalanceOne
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneAccountBalanceOne,
false,
v,
&resp,
spotAccountAssetInfo)
if err != nil {
return UserBalanceData{}, err
}
return resp.Data, nil
}
// PlaceSpotOrder creates an order
func (c *Coinbene) PlaceSpotOrder(price, quantity float64, symbol, direction,
orderType, clientID string, notional int) (OrderPlacementResponse, error) {
var resp OrderPlacementResponse
params := url.Values{}
switch direction {
case order.Buy.Lower():
params.Set("direction", buyDirection)
case order.Sell.Lower():
params.Set("direction", sellDirection)
default:
return resp,
fmt.Errorf("invalid direction '%v', must be either 'buy' or 'sell'",
direction)
}
switch orderType {
case order.Limit.Lower():
params.Set("orderType", limitOrder)
case order.Market.Lower():
params.Set("orderType", marketOrder)
case order.PostOnly.Lower():
params.Set("orderType", postOnlyOrder)
case order.FillOrKill.Lower():
params.Set("orderType", fillOrKillOrder)
case order.IOS.Lower():
params.Set("orderType", iosOrder)
default:
return resp,
errors.New("invalid order type, must be either 'limit', 'market', 'postOnly', 'fillOrKill', 'ios'")
}
params.Set("symbol", symbol)
params.Set("price", strconv.FormatFloat(price, 'f', -1, 64))
params.Set("quantity", strconv.FormatFloat(quantity, 'f', -1, 64))
if clientID != "" {
params.Set("clientId", clientID)
}
if notional != 0 {
params.Set("notional", strconv.Itoa(notional))
}
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbenePlaceOrder
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbenePlaceOrder,
false,
params,
&resp,
spotPlaceOrder)
if err != nil {
return resp, err
}
return resp, nil
}
// PlaceSpotOrders sets a batchful order request
func (c *Coinbene) PlaceSpotOrders(orders []PlaceOrderRequest) ([]OrderPlacementResponse, error) {
if len(orders) == 0 {
return nil, errors.New("orders is nil")
}
type ord struct {
Symbol string `json:"symbol"`
Direction string `json:"direction"`
Price string `json:"price"`
Quantity string `json:"quantity"`
OrderType string `json:"orderType"`
Notional string `json:"notional,omitempty"`
ClientID string `json:"clientId,omitempty"`
}
var reqOrders []ord
for x := range orders {
o := ord{
Symbol: orders[x].Symbol,
Price: strconv.FormatFloat(orders[x].Price, 'f', -1, 64),
Quantity: strconv.FormatFloat(orders[x].Quantity, 'f', -1, 64),
}
switch orders[x].Direction {
case order.Buy.Lower():
o.Direction = buyDirection
case order.Sell.Lower():
o.Direction = sellDirection
default:
return nil,
fmt.Errorf("invalid direction '%v', must be either 'buy' or 'sell'",
orders[x].Direction)
}
switch orders[x].OrderType {
case order.Limit.Lower():
o.OrderType = limitOrder
case order.Market.Lower():
o.OrderType = marketOrder
default:
return nil,
errors.New("invalid order type, must be either 'limit' or 'market'")
}
if orders[x].ClientID != "" {
o.ClientID = orders[x].ClientID
}
if orders[x].Notional != 0 {
o.Notional = strconv.Itoa(orders[x].Notional)
}
reqOrders = append(reqOrders, o)
}
resp := struct {
Data []OrderPlacementResponse `json:"data"`
}{}
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneBatchPlaceOrder
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbeneBatchPlaceOrder,
false,
reqOrders,
&resp,
spotBatchOrder)
if err != nil {
return nil, err
}
return resp.Data, nil
}
// FetchOpenSpotOrders finds open orders
func (c *Coinbene) FetchOpenSpotOrders(symbol string) (OrdersInfo, error) {
params := url.Values{}
params.Set("symbol", symbol)
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneOpenOrders
var orders OrdersInfo
for i := int64(1); ; i++ {
temp := struct {
Data OrdersInfo `json:"data"`
}{}
params.Set("pageNum", strconv.FormatInt(i, 10))
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneOpenOrders,
false,
params,
&temp,
spotQueryOpenOrders)
if err != nil {
return nil, err
}
for j := range temp.Data {
orders = append(orders, temp.Data[j])
}
if len(temp.Data) != 20 {
break
}
}
return orders, nil
}
// FetchClosedOrders finds open orders
func (c *Coinbene) FetchClosedOrders(symbol, latestID string) (OrdersInfo, error) {
params := url.Values{}
params.Set("symbol", symbol)
params.Set("latestOrderId", latestID)
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneClosedOrders
var orders OrdersInfo
for i := int64(1); ; i++ {
temp := struct {
Data OrdersInfo `json:"data"`
}{}
params.Set("pageNum", strconv.FormatInt(i, 10))
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneClosedOrders,
false,
params,
&temp,
spotQueryClosedOrders)
if err != nil {
return nil, err
}
for j := range temp.Data {
orders = append(orders, temp.Data[j])
}
if len(temp.Data) != 20 {
break
}
}
return orders, nil
}
// FetchSpotOrderInfo gets order info
func (c *Coinbene) FetchSpotOrderInfo(orderID string) (OrderInfo, error) {
resp := struct {
Data OrderInfo `json:"data"`
}{}
params := url.Values{}
params.Set("orderId", orderID)
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneOrderInfo
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneOrderInfo,
false,
params,
&resp,
spotQuerySpecficOrder)
if err != nil {
return resp.Data, err
}
if resp.Data.OrderID != orderID {
return resp.Data, fmt.Errorf("%s orderID doesn't match the returned orderID %s",
orderID, resp.Data.OrderID)
}
return resp.Data, nil
}
// GetSpotOrderFills returns a list of fills related to an order ID
func (c *Coinbene) GetSpotOrderFills(orderID string) ([]OrderFills, error) {
resp := struct {
Data []OrderFills `json:"data"`
}{}
params := url.Values{}
params.Set("orderId", orderID)
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneTradeFills
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneTradeFills,
false,
params,
&resp,
spotQueryTradeFills)
if err != nil {
return nil, err
}
return resp.Data, nil
}
// CancelSpotOrder removes a given order
func (c *Coinbene) CancelSpotOrder(orderID string) (string, error) {
resp := struct {
Data string `json:"data"`
}{}
req := make(map[string]interface{})
req["orderId"] = orderID
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneCancelOrder
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbeneCancelOrder,
false,
req,
&resp,
spotCancelOrder)
if err != nil {
return "", err
}
return resp.Data, nil
}
// CancelSpotOrders cancels a batch of orders
func (c *Coinbene) CancelSpotOrders(orderIDs []string) ([]OrderCancellationResponse, error) {
req := make(map[string]interface{})
req["orderIds"] = orderIDs
type resp struct {
Data []OrderCancellationResponse `json:"data"`
}
var r resp
path := c.API.Endpoints.URL + coinbeneAPIVersion + coinbeneBatchCancel
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbeneBatchCancel,
false,
req,
&r,
spotCancelOrdersBatch)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapTickers returns a map of swap tickers
func (c *Coinbene) GetSwapTickers() (SwapTickers, error) {
type resp struct {
Data SwapTickers `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneGetTickers
err := c.SendHTTPRequest(path, contractTickers, &r)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapTicker returns a specific swap ticker
func (c *Coinbene) GetSwapTicker(symbol string) (SwapTicker, error) {
tickers, err := c.GetSwapTickers()
if err != nil {
return SwapTicker{}, err
}
t, ok := tickers[strings.ToUpper(symbol)]
if !ok {
return SwapTicker{},
fmt.Errorf("symbol %s not found in tickers map", symbol)
}
return t, nil
}
// GetSwapOrderbook returns an orderbook for the specified currency
func (c *Coinbene) GetSwapOrderbook(symbol string, size int64) (Orderbook, error) {
var s Orderbook
if symbol == "" {
return s, fmt.Errorf("a symbol must be specified")
}
v := url.Values{}
v.Set("symbol", symbol)
if size != 0 {
v.Set("size", strconv.FormatInt(size, 10))
}
type resp struct {
Data struct {
Asks [][]string `json:"asks"`
Bids [][]string `json:"bids"`
Time time.Time `json:"timestamp"`
Symbol string `json:"symbol"`
} `json:"data"`
}
var r resp
path := common.EncodeURLValues(coinbeneSwapAPIURL+coinbeneAPIVersion+coinbeneGetOrderBook, v)
err := c.SendHTTPRequest(path, contractOrderbook, &r)
if err != nil {
return s, err
}
processOB := func(ob [][]string) ([]OrderbookItem, error) {
var o []OrderbookItem
for x := range ob {
var price, amount float64
var count int64
count, err = strconv.ParseInt(ob[x][2], 10, 64)
if err != nil {
return nil, err
}
price, err = strconv.ParseFloat(ob[x][0], 64)
if err != nil {
return nil, err
}
amount, err = strconv.ParseFloat(ob[x][1], 64)
if err != nil {
return nil, err
}
o = append(o, OrderbookItem{Price: price,
Amount: amount,
Count: count,
})
}
return o, nil
}
s.Bids, err = processOB(r.Data.Bids)
if err != nil {
return s, err
}
s.Asks, err = processOB(r.Data.Asks)
if err != nil {
return s, err
}
s.Time = r.Data.Time
s.Symbol = r.Data.Symbol
return s, nil
}
// GetKlines data returns the kline data for a specific symbol
func (c *Coinbene) GetKlines(pair string, start, end time.Time, period string) (resp CandleResponse, err error) {
v := url.Values{}
v.Add("symbol", pair)
if !start.IsZero() {
v.Add("start", strconv.FormatInt(start.Unix(), 10))
}
if !end.IsZero() {
v.Add("end", strconv.FormatInt(end.Unix(), 10))
}
v.Add("period", period)
path := common.EncodeURLValues(coinbeneAPIURL+coinbeneAPIVersion+coinbeneSpotKlines, v)
if err = c.SendHTTPRequest(path, contractKline, &resp); err != nil {
return
}
if resp.Code != 200 {
return resp, errors.New(resp.Message)
}
return
}
// GetSwapKlines data returns the kline data for a specific symbol
func (c *Coinbene) GetSwapKlines(symbol string, start, end time.Time, resolution string) (resp CandleResponse, err error) {
v := url.Values{}
v.Set("symbol", symbol)
if !start.IsZero() {
v.Add("startTime", strconv.FormatInt(start.Unix(), 10))
}
if !end.IsZero() {
v.Add("endTime", strconv.FormatInt(end.Unix(), 10))
}
v.Set("resolution", resolution)
path := common.EncodeURLValues(coinbeneSwapAPIURL+coinbeneAPIVersion+coinbeneGetKlines, v)
if err = c.SendHTTPRequest(path, contractKline, &resp); err != nil {
return
}
return
}
// GetSwapTrades returns a list of trades for a swap symbol
func (c *Coinbene) GetSwapTrades(symbol string, limit int) (SwapTrades, error) {
v := url.Values{}
v.Set("symbol", symbol)
if limit != 0 {
v.Set("limit", strconv.Itoa(limit))
}
type resp struct {
Data [][]string `json:"data"`
}
var r resp
path := common.EncodeURLValues(coinbeneSwapAPIURL+coinbeneAPIVersion+coinbeneGetTrades, v)
if err := c.SendHTTPRequest(path, contractTrades, &r); err != nil {
return nil, err
}
var s SwapTrades
for x := range r.Data {
tm, err := time.Parse(time.RFC3339, r.Data[x][3])
if err != nil {
return nil, err
}
price, err := strconv.ParseFloat(r.Data[x][0], 64)
if err != nil {
return nil, err
}
orderSide := order.Buy
if r.Data[x][1] == "s" {
orderSide = order.Sell
}
volume, err := strconv.ParseFloat(r.Data[x][2], 64)
if err != nil {
return nil, err
}
s = append(s, SwapTrade{
Price: price,
Side: orderSide,
Volume: volume,
Time: tm,
})
}
return s, nil
}
// GetSwapAccountInfo returns a users swap account balance info
func (c *Coinbene) GetSwapAccountInfo() (SwapAccountInfo, error) {
type resp struct {
Data SwapAccountInfo `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneAccountInfo
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneAccountInfo,
true,
nil,
&r,
contractAccountInfo)
if err != nil {
return SwapAccountInfo{}, err
}
return r.Data, nil
}
// GetSwapPositions returns a list of open swap positions
func (c *Coinbene) GetSwapPositions(symbol string) (SwapPositions, error) {
v := url.Values{}
v.Set("symbol", symbol)
type resp struct {
Data SwapPositions `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneListSwapPositions
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneListSwapPositions,
true,
v,
&r,
contractPositionInfo)
if err != nil {
return nil, err
}
return r.Data, nil
}
// PlaceSwapOrder places a swap order
func (c *Coinbene) PlaceSwapOrder(symbol, direction, orderType, marginMode,
clientID string, price, quantity float64, leverage int) (SwapPlaceOrderResponse, error) {
v := url.Values{}
v.Set("symbol", symbol)
switch direction {
case order.Buy.Lower():
v.Set("direction", openLong)
case order.Sell.Lower():
v.Set("direction", openShort)
default:
return SwapPlaceOrderResponse{},
fmt.Errorf("invalid direction '%v', must be either 'buy' or 'sell'",
direction)
}
switch orderType {
case order.Limit.Lower():
v.Set("orderType", limitOrder)
case order.Market.Lower():
v.Set("orderType", marketOrder)
default:
return SwapPlaceOrderResponse{},
errors.New("invalid order type, must be either 'limit' or 'market'")
}
v.Set("leverage", strconv.Itoa(leverage))
v.Set("orderPrice", strconv.FormatFloat(price, 'f', -1, 64))
v.Set("quantity", strconv.FormatFloat(quantity, 'f', -1, 64))
if marginMode != "" {
v.Set("marginMode", marginMode)
}
if clientID != "" {
v.Set("clientId", clientID)
}
type resp struct {
Data SwapPlaceOrderResponse `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbenePlaceOrder
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbenePlaceOrder,
true,
v,
&r,
contractPlaceOrder)
if err != nil {
return SwapPlaceOrderResponse{}, err
}
return r.Data, nil
}
// CancelSwapOrder cancels a swap order
func (c *Coinbene) CancelSwapOrder(orderID string) (string, error) {
params := make(map[string]interface{})
params["orderId"] = orderID
type resp struct {
Data string `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneCancelOrder
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbeneCancelOrder,
true,
params,
&r,
contractCancelOrder)
if err != nil {
return "", err
}
return r.Data, nil
}
// GetSwapOpenOrders gets a list of open swap orders
func (c *Coinbene) GetSwapOpenOrders(symbol string, pageNum, pageSize int) (SwapOrders, error) {
v := url.Values{}
v.Set("symbol", symbol)
if pageNum != 0 {
v.Set("pageNum", strconv.Itoa(pageNum))
}
if pageSize != 0 {
v.Set("pageSize", strconv.Itoa(pageSize))
}
type resp struct {
Data SwapOrders `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneOpenOrders
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneOpenOrders,
true,
v,
&r,
contractGetOpenOrders)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapOpenOrdersByPage gets a list of open orders by page
func (c *Coinbene) GetSwapOpenOrdersByPage(symbol string, latestOrderID int64) (SwapOrders, error) {
v := url.Values{}
if symbol != "" {
v.Set("symbol", symbol)
}
if latestOrderID != 0 {
v.Set("latestOrderId", strconv.FormatInt(latestOrderID, 10))
}
type resp struct {
Data SwapOrders `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneOpenOrdersByPage
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneOpenOrdersByPage,
true,
v,
&r,
contractOpenOrdersByPage)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapOrderInfo gets order info for a specific order
func (c *Coinbene) GetSwapOrderInfo(orderID string) (SwapOrder, error) {
v := url.Values{}
v.Set("orderId", orderID)
type resp struct {
Data SwapOrder `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneOrderInfo
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneOrderInfo,
true,
v,
&r,
contractGetOrderInfo)
if err != nil {
return SwapOrder{}, err
}
return r.Data, nil
}
// GetSwapOrderHistory returns the swap order history for a given symbol
func (c *Coinbene) GetSwapOrderHistory(beginTime, endTime, symbol string, pageNum,
pageSize int, direction, orderType string) (SwapOrders, error) {
v := url.Values{}
if beginTime != "" {
v.Set("beginTime", beginTime)
}
if endTime != "" {
v.Set("endTime", endTime)
}
v.Set("symbol", symbol)
if pageNum != 0 {
v.Set("pageNum", strconv.Itoa(pageNum))
}
if pageSize != 0 {
v.Set("pageSize", strconv.Itoa(pageSize))
}
if direction != "" {
v.Set("direction", direction)
}
if orderType != "" {
v.Set("orderType", orderType)
}
type resp struct {
Data SwapOrders `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneClosedOrders
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneClosedOrders,
true,
v,
&r,
contractGetClosedOrders)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapOrderHistoryByOrderID returns a list of historic orders based on user params
func (c *Coinbene) GetSwapOrderHistoryByOrderID(beginTime, endTime, symbol, status string,
latestOrderID int64) (SwapOrders, error) {
v := url.Values{}
if beginTime != "" {
v.Set("beginTime", beginTime)
}
if endTime != "" {
v.Set("endTime", endTime)
}
if symbol != "" {
v.Set("symbol", symbol)
}
if status != "" {
v.Set("status", status)
}
if latestOrderID != 0 {
v.Set("latestOrderId", strconv.FormatInt(latestOrderID, 10))
}
type resp struct {
Data SwapOrders `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneClosedOrdersByPage
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneClosedOrdersByPage,
true,
v,
&r,
contractGetClosedOrdersbyPage)
if err != nil {
return nil, err
}
return r.Data, nil
}
// CancelSwapOrders cancels multiple swap order IDs
func (c *Coinbene) CancelSwapOrders(orderIDs []string) ([]OrderCancellationResponse, error) {
if len(orderIDs) > 10 {
return nil, errors.New("only 10 orderIDs are allowed at a time")
}
req := make(map[string]interface{})
req["orderIds"] = orderIDs
type resp struct {
Data []OrderCancellationResponse `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneBatchCancel
err := c.SendAuthHTTPRequest(http.MethodPost,
path,
coinbeneBatchCancel,
true,
req,
&r,
contractCancelMultipleOrders)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapOrderFills returns a list of swap order fills
func (c *Coinbene) GetSwapOrderFills(symbol, orderID string, lastTradeID int64) (SwapOrderFills, error) {
v := url.Values{}
if symbol != "" {
v.Set("symbol", symbol)
}
if orderID != "" {
v.Set("orderId", orderID)
}
if lastTradeID != 0 {
v.Set("lastTradedId", strconv.FormatInt(lastTradeID, 10))
}
type resp struct {
Data SwapOrderFills `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbeneOrderFills
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbeneOrderFills,
true,
v,
&r,
contractGetOrderFills)
if err != nil {
return nil, err
}
return r.Data, nil
}
// GetSwapFundingRates returns a list of funding rates
func (c *Coinbene) GetSwapFundingRates(pageNum, pageSize int) ([]SwapFundingRate, error) {
v := url.Values{}
if pageNum != 0 {
v.Set("pageNum", strconv.Itoa(pageNum))
}
if pageSize != 0 {
v.Set("pageSize", strconv.Itoa(pageSize))
}
type resp struct {
Data []SwapFundingRate `json:"data"`
}
var r resp
path := coinbeneSwapAPIURL + coinbeneAPIVersion + coinbenePositionFeeRate
err := c.SendAuthHTTPRequest(http.MethodGet,
path,
coinbenePositionFeeRate,
true,
v,
&r,
contractGetFundingRates)
if err != nil {
return nil, err
}
return r.Data, nil
}
// SendHTTPRequest sends an unauthenticated HTTP request
func (c *Coinbene) SendHTTPRequest(path string, f request.EndpointLimit, result interface{}) error {
var resp json.RawMessage
errCap := struct {
Code int `json:"code"`
Message string `json:"message"`
}{}
if err := c.SendPayload(context.Background(), &request.Item{
Method: http.MethodGet,
Path: path,
Result: &resp,
Verbose: c.Verbose,
HTTPDebugging: c.HTTPDebugging,
HTTPRecording: c.HTTPRecording,
Endpoint: f,
}); err != nil {
return err
}
if err := json.Unmarshal(resp, &errCap); err == nil {
if errCap.Code != 200 && errCap.Message != "" {
return errors.New(errCap.Message)
}
}
return json.Unmarshal(resp, result)
}
// SendAuthHTTPRequest sends an authenticated HTTP request
func (c *Coinbene) SendAuthHTTPRequest(method, path, epPath string, isSwap bool,
params, result interface{}, f request.EndpointLimit) error {
if !c.AllowAuthenticatedRequest() {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
c.Name)
}
authPath := coinbeneAuthPath
if isSwap {
authPath = coinbeneSwapAuthPath
}
now := time.Now()
timestamp := now.UTC().Format("2006-01-02T15:04:05.999Z")
var finalBody io.Reader
var preSign string
switch {
case params != nil && method == http.MethodGet:
p, ok := params.(url.Values)
if !ok {
return fmt.Errorf("params is not of type url.Values")
}
preSign = timestamp + method + authPath + epPath + "?" + p.Encode()
path = common.EncodeURLValues(path, p)
case params != nil:
var i interface{}
switch p := params.(type) {
case url.Values:
m := make(map[string]string)
for k, v := range p {
m[k] = strings.Join(v, "")
}
i = m
default:
i = p
}
tempBody, err := json.Marshal(i)
if err != nil {
return err
}
finalBody = bytes.NewBufferString(string(tempBody))
preSign = timestamp + method + authPath + epPath + string(tempBody)
default:
preSign = timestamp + method + authPath + epPath
}
tempSign := crypto.GetHMAC(crypto.HashSHA256,
[]byte(preSign),
[]byte(c.API.Credentials.Secret))
headers := make(map[string]string)
headers["Content-Type"] = "application/json"
headers["ACCESS-KEY"] = c.API.Credentials.Key
headers["ACCESS-SIGN"] = crypto.HexEncodeToString(tempSign)
headers["ACCESS-TIMESTAMP"] = timestamp
var resp json.RawMessage
errCap := struct {
Code int `json:"code"`
Message string `json:"message"`
}{}
// Expiry of timestamp doesn't appear to be documented, so making a reasonable assumption
ctx, cancel := context.WithDeadline(context.Background(), now.Add(15*time.Second))
defer cancel()
if err := c.SendPayload(ctx, &request.Item{
Method: method,
Path: path,
Headers: headers,
Body: finalBody,
Result: &resp,
AuthRequest: true,
Verbose: c.Verbose,
HTTPDebugging: c.HTTPDebugging,
HTTPRecording: c.HTTPRecording,
}); err != nil {
return err
}
if err := json.Unmarshal(resp, &errCap); err == nil {
if errCap.Code != 200 && errCap.Message != "" {
return errors.New(errCap.Message)
}
}
return json.Unmarshal(resp, result)
}