mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-29 15:10:37 +00:00
* 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
1187 lines
30 KiB
Go
1187 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, limit int64) (Trades, error) {
|
|
resp := struct {
|
|
Data [][]string `json:"data"`
|
|
}{}
|
|
|
|
params := url.Values{}
|
|
params.Set("symbol", symbol)
|
|
params.Set("limit", strconv.FormatInt(limit, 10))
|
|
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)
|
|
}
|