mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-21 07:26:48 +00:00
* 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
825 lines
27 KiB
Go
825 lines
27 KiB
Go
package coinbasepro
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"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/order"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
|
|
"github.com/thrasher-corp/gocryptotrader/log"
|
|
)
|
|
|
|
const (
|
|
coinbaseproAPIURL = "https://api.pro.coinbase.com/"
|
|
coinbaseproSandboxAPIURL = "https://api-public.sandbox.pro.coinbase.com/"
|
|
coinbaseproAPIVersion = "0"
|
|
coinbaseproProducts = "products"
|
|
coinbaseproOrderbook = "book"
|
|
coinbaseproTicker = "ticker"
|
|
coinbaseproTrades = "trades"
|
|
coinbaseproHistory = "candles"
|
|
coinbaseproStats = "stats"
|
|
coinbaseproCurrencies = "currencies"
|
|
coinbaseproAccounts = "accounts"
|
|
coinbaseproLedger = "ledger"
|
|
coinbaseproHolds = "holds"
|
|
coinbaseproOrders = "orders"
|
|
coinbaseproFills = "fills"
|
|
coinbaseproTransfers = "transfers"
|
|
coinbaseproReports = "reports"
|
|
coinbaseproTime = "time"
|
|
coinbaseproMarginTransfer = "profiles/margin-transfer"
|
|
coinbaseproPosition = "position"
|
|
coinbaseproPositionClose = "position/close"
|
|
coinbaseproPaymentMethod = "payment-methods"
|
|
coinbaseproPaymentMethodDeposit = "deposits/payment-method"
|
|
coinbaseproDepositCoinbase = "deposits/coinbase-account"
|
|
coinbaseproWithdrawalPaymentMethod = "withdrawals/payment-method"
|
|
coinbaseproWithdrawalCoinbase = "withdrawals/coinbase"
|
|
coinbaseproWithdrawalCrypto = "withdrawals/crypto"
|
|
coinbaseproCoinbaseAccounts = "coinbase-accounts"
|
|
coinbaseproTrailingVolume = "users/self/trailing-volume"
|
|
)
|
|
|
|
// CoinbasePro is the overarching type across the coinbasepro package
|
|
type CoinbasePro struct {
|
|
exchange.Base
|
|
}
|
|
|
|
// GetProducts returns supported currency pairs on the exchange with specific
|
|
// information about the pair
|
|
func (c *CoinbasePro) GetProducts() ([]Product, error) {
|
|
var products []Product
|
|
|
|
return products, c.SendHTTPRequest(c.API.Endpoints.URL+coinbaseproProducts, &products)
|
|
}
|
|
|
|
// GetOrderbook returns orderbook by currency pair and level
|
|
func (c *CoinbasePro) GetOrderbook(symbol string, level int) (interface{}, error) {
|
|
orderbook := OrderbookResponse{}
|
|
|
|
path := fmt.Sprintf("%s/%s/%s", c.API.Endpoints.URL+coinbaseproProducts, symbol, coinbaseproOrderbook)
|
|
if level > 0 {
|
|
levelStr := strconv.Itoa(level)
|
|
path = fmt.Sprintf("%s/%s/%s?level=%s", c.API.Endpoints.URL+coinbaseproProducts, symbol, coinbaseproOrderbook, levelStr)
|
|
}
|
|
|
|
if err := c.SendHTTPRequest(path, &orderbook); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if level == 3 {
|
|
ob := OrderbookL3{}
|
|
ob.Sequence = orderbook.Sequence
|
|
for _, x := range orderbook.Asks {
|
|
price, err := strconv.ParseFloat((x[0].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
amount, err := strconv.ParseFloat((x[1].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
ob.Asks = append(ob.Asks, OrderL3{Price: price, Amount: amount, OrderID: x[2].(string)})
|
|
}
|
|
for _, x := range orderbook.Bids {
|
|
price, err := strconv.ParseFloat((x[0].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
amount, err := strconv.ParseFloat((x[1].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
ob.Bids = append(ob.Bids, OrderL3{Price: price, Amount: amount, OrderID: x[2].(string)})
|
|
}
|
|
return ob, nil
|
|
}
|
|
ob := OrderbookL1L2{}
|
|
ob.Sequence = orderbook.Sequence
|
|
for _, x := range orderbook.Asks {
|
|
price, err := strconv.ParseFloat((x[0].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
amount, err := strconv.ParseFloat((x[1].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
ob.Asks = append(ob.Asks, OrderL1L2{Price: price, Amount: amount, NumOrders: x[2].(float64)})
|
|
}
|
|
for _, x := range orderbook.Bids {
|
|
price, err := strconv.ParseFloat((x[0].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
amount, err := strconv.ParseFloat((x[1].(string)), 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
ob.Bids = append(ob.Bids, OrderL1L2{Price: price, Amount: amount, NumOrders: x[2].(float64)})
|
|
}
|
|
return ob, nil
|
|
}
|
|
|
|
// GetTicker returns ticker by currency pair
|
|
// currencyPair - example "BTC-USD"
|
|
func (c *CoinbasePro) GetTicker(currencyPair string) (Ticker, error) {
|
|
tick := Ticker{}
|
|
path := fmt.Sprintf(
|
|
"%s/%s/%s", c.API.Endpoints.URL+coinbaseproProducts, currencyPair, coinbaseproTicker)
|
|
return tick, c.SendHTTPRequest(path, &tick)
|
|
}
|
|
|
|
// GetTrades listd the latest trades for a product
|
|
// currencyPair - example "BTC-USD"
|
|
func (c *CoinbasePro) GetTrades(currencyPair string) ([]Trade, error) {
|
|
var trades []Trade
|
|
path := fmt.Sprintf(
|
|
"%s/%s/%s", c.API.Endpoints.URL+coinbaseproProducts, currencyPair, coinbaseproTrades)
|
|
return trades, c.SendHTTPRequest(path, &trades)
|
|
}
|
|
|
|
// GetHistoricRates returns historic rates for a product. Rates are returned in
|
|
// grouped buckets based on requested granularity.
|
|
func (c *CoinbasePro) GetHistoricRates(currencyPair, start, end string, granularity int64) ([]History, error) {
|
|
var resp [][]interface{}
|
|
var history []History
|
|
values := url.Values{}
|
|
|
|
if len(start) > 0 {
|
|
values.Set("start", start)
|
|
} else {
|
|
values.Set("start", "")
|
|
}
|
|
|
|
if len(end) > 0 {
|
|
values.Set("end", end)
|
|
} else {
|
|
values.Set("end", "")
|
|
}
|
|
|
|
allowedGranularities := [6]int64{60, 300, 900, 3600, 21600, 86400}
|
|
validGran, _ := common.InArray(granularity, allowedGranularities)
|
|
if !validGran {
|
|
return nil, errors.New("Invalid granularity value: " + strconv.FormatInt(granularity, 10) + ". Allowed values are {60, 300, 900, 3600, 21600, 86400}")
|
|
}
|
|
if granularity > 0 {
|
|
values.Set("granularity", strconv.FormatInt(granularity, 10))
|
|
}
|
|
|
|
path := common.EncodeURLValues(
|
|
fmt.Sprintf("%s/%s/%s", c.API.Endpoints.URL+coinbaseproProducts, currencyPair, coinbaseproHistory),
|
|
values)
|
|
|
|
if err := c.SendHTTPRequest(path, &resp); err != nil {
|
|
return history, err
|
|
}
|
|
|
|
for _, single := range resp {
|
|
var s History
|
|
a, _ := single[0].(float64)
|
|
s.Time = int64(a)
|
|
b, _ := single[1].(float64)
|
|
s.Low = b
|
|
c, _ := single[2].(float64)
|
|
s.High = c
|
|
d, _ := single[3].(float64)
|
|
s.Open = d
|
|
e, _ := single[4].(float64)
|
|
s.Close = e
|
|
f, _ := single[5].(float64)
|
|
s.Volume = f
|
|
history = append(history, s)
|
|
}
|
|
|
|
return history, nil
|
|
}
|
|
|
|
// GetStats returns a 24 hr stat for the product. Volume is in base currency
|
|
// units. open, high, low are in quote currency units.
|
|
func (c *CoinbasePro) GetStats(currencyPair string) (Stats, error) {
|
|
stats := Stats{}
|
|
path := fmt.Sprintf(
|
|
"%s/%s/%s", c.API.Endpoints.URL+coinbaseproProducts, currencyPair, coinbaseproStats)
|
|
|
|
return stats, c.SendHTTPRequest(path, &stats)
|
|
}
|
|
|
|
// GetCurrencies returns a list of supported currency on the exchange
|
|
// Warning: Not all currencies may be currently in use for tradinc.
|
|
func (c *CoinbasePro) GetCurrencies() ([]Currency, error) {
|
|
var currencies []Currency
|
|
|
|
return currencies, c.SendHTTPRequest(c.API.Endpoints.URL+coinbaseproCurrencies, ¤cies)
|
|
}
|
|
|
|
// GetServerTime returns the API server time
|
|
func (c *CoinbasePro) GetServerTime() (ServerTime, error) {
|
|
serverTime := ServerTime{}
|
|
|
|
return serverTime, c.SendHTTPRequest(c.API.Endpoints.URL+coinbaseproTime, &serverTime)
|
|
}
|
|
|
|
// GetAccounts returns a list of trading accounts associated with the APIKEYS
|
|
func (c *CoinbasePro) GetAccounts() ([]AccountResponse, error) {
|
|
var resp []AccountResponse
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, coinbaseproAccounts, nil, &resp)
|
|
}
|
|
|
|
// GetAccount returns information for a single account. Use this endpoint when
|
|
// account_id is known
|
|
func (c *CoinbasePro) GetAccount(accountID string) (AccountResponse, error) {
|
|
resp := AccountResponse{}
|
|
path := fmt.Sprintf("%s/%s", coinbaseproAccounts, accountID)
|
|
|
|
return resp, c.SendAuthenticatedHTTPRequest(http.MethodGet, path, nil, &resp)
|
|
}
|
|
|
|
// GetAccountHistory returns a list of account activity. Account activity either
|
|
// increases or decreases your account balance. Items are paginated and sorted
|
|
// latest first.
|
|
func (c *CoinbasePro) GetAccountHistory(accountID string) ([]AccountLedgerResponse, error) {
|
|
var resp []AccountLedgerResponse
|
|
path := fmt.Sprintf("%s/%s/%s", coinbaseproAccounts, accountID, coinbaseproLedger)
|
|
|
|
return resp, c.SendAuthenticatedHTTPRequest(http.MethodGet, path, nil, &resp)
|
|
}
|
|
|
|
// GetHolds returns the holds that are placed on an account for any active
|
|
// orders or pending withdraw requests. As an order is filled, the hold amount
|
|
// is updated. If an order is canceled, any remaining hold is removed. For a
|
|
// withdraw, once it is completed, the hold is removed.
|
|
func (c *CoinbasePro) GetHolds(accountID string) ([]AccountHolds, error) {
|
|
var resp []AccountHolds
|
|
path := fmt.Sprintf("%s/%s/%s", coinbaseproAccounts, accountID, coinbaseproHolds)
|
|
|
|
return resp, c.SendAuthenticatedHTTPRequest(http.MethodGet, path, nil, &resp)
|
|
}
|
|
|
|
// PlaceLimitOrder places a new limit order. Orders can only be placed if the
|
|
// account has sufficient funds. Once an order is placed, account funds
|
|
// will be put on hold for the duration of the order. How much and which funds
|
|
// are put on hold depends on the order type and parameters specified.
|
|
//
|
|
// GENERAL PARAMS
|
|
// clientRef - [optional] Order ID selected by you to identify your order
|
|
// side - buy or sell
|
|
// productID - A valid product id
|
|
// stp - [optional] Self-trade prevention flag
|
|
//
|
|
// LIMIT ORDER PARAMS
|
|
// price - Price per bitcoin
|
|
// amount - Amount of BTC to buy or sell
|
|
// timeInforce - [optional] GTC, GTT, IOC, or FOK (default is GTC)
|
|
// cancelAfter - [optional] min, hour, day * Requires time_in_force to be GTT
|
|
// postOnly - [optional] Post only flag Invalid when time_in_force is IOC or FOK
|
|
func (c *CoinbasePro) PlaceLimitOrder(clientRef string, price, amount float64, side, timeInforce, cancelAfter, productID, stp string, postOnly bool) (string, error) {
|
|
resp := GeneralizedOrderResponse{}
|
|
req := make(map[string]interface{})
|
|
req["type"] = order.Limit.Lower()
|
|
req["price"] = strconv.FormatFloat(price, 'f', -1, 64)
|
|
req["size"] = strconv.FormatFloat(amount, 'f', -1, 64)
|
|
req["side"] = side
|
|
req["product_id"] = productID
|
|
|
|
if cancelAfter != "" {
|
|
req["cancel_after"] = cancelAfter
|
|
}
|
|
if timeInforce != "" {
|
|
req["time_in_foce"] = timeInforce
|
|
}
|
|
if clientRef != "" {
|
|
req["client_oid"] = clientRef
|
|
}
|
|
if stp != "" {
|
|
req["stp"] = stp
|
|
}
|
|
if postOnly {
|
|
req["post_only"] = postOnly
|
|
}
|
|
|
|
err := c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproOrders, req, &resp)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return resp.ID, nil
|
|
}
|
|
|
|
// PlaceMarketOrder places a new market order.
|
|
// Orders can only be placed if the account has sufficient funds. Once an order
|
|
// is placed, account funds will be put on hold for the duration of the order.
|
|
// How much and which funds are put on hold depends on the order type and
|
|
// parameters specified.
|
|
//
|
|
// GENERAL PARAMS
|
|
// clientRef - [optional] Order ID selected by you to identify your order
|
|
// side - buy or sell
|
|
// productID - A valid product id
|
|
// stp - [optional] Self-trade prevention flag
|
|
//
|
|
// MARKET ORDER PARAMS
|
|
// size - [optional]* Desired amount in BTC
|
|
// funds [optional]* Desired amount of quote currency to use
|
|
// * One of size or funds is required.
|
|
func (c *CoinbasePro) PlaceMarketOrder(clientRef string, size, funds float64, side, productID, stp string) (string, error) {
|
|
resp := GeneralizedOrderResponse{}
|
|
req := make(map[string]interface{})
|
|
req["side"] = side
|
|
req["product_id"] = productID
|
|
req["type"] = order.Market.Lower()
|
|
|
|
if size != 0 {
|
|
req["size"] = strconv.FormatFloat(size, 'f', -1, 64)
|
|
}
|
|
if funds != 0 {
|
|
req["funds"] = strconv.FormatFloat(funds, 'f', -1, 64)
|
|
}
|
|
if clientRef != "" {
|
|
req["client_oid"] = clientRef
|
|
}
|
|
if stp != "" {
|
|
req["stp"] = stp
|
|
}
|
|
|
|
err := c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproOrders, req, &resp)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return resp.ID, nil
|
|
}
|
|
|
|
// PlaceMarginOrder places a new market order.
|
|
// Orders can only be placed if the account has sufficient funds. Once an order
|
|
// is placed, account funds will be put on hold for the duration of the order.
|
|
// How much and which funds are put on hold depends on the order type and
|
|
// parameters specified.
|
|
//
|
|
// GENERAL PARAMS
|
|
// clientRef - [optional] Order ID selected by you to identify your order
|
|
// side - buy or sell
|
|
// productID - A valid product id
|
|
// stp - [optional] Self-trade prevention flag
|
|
//
|
|
// MARGIN ORDER PARAMS
|
|
// size - [optional]* Desired amount in BTC
|
|
// funds - [optional]* Desired amount of quote currency to use
|
|
func (c *CoinbasePro) PlaceMarginOrder(clientRef string, size, funds float64, side, productID, stp string) (string, error) {
|
|
resp := GeneralizedOrderResponse{}
|
|
req := make(map[string]interface{})
|
|
req["side"] = side
|
|
req["product_id"] = productID
|
|
req["type"] = "margin"
|
|
|
|
if size != 0 {
|
|
req["size"] = strconv.FormatFloat(size, 'f', -1, 64)
|
|
}
|
|
if funds != 0 {
|
|
req["funds"] = strconv.FormatFloat(funds, 'f', -1, 64)
|
|
}
|
|
if clientRef != "" {
|
|
req["client_oid"] = clientRef
|
|
}
|
|
if stp != "" {
|
|
req["stp"] = stp
|
|
}
|
|
|
|
err := c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproOrders, req, &resp)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return resp.ID, nil
|
|
}
|
|
|
|
// CancelExistingOrder cancels order by orderID
|
|
func (c *CoinbasePro) CancelExistingOrder(orderID string) error {
|
|
path := fmt.Sprintf("%s/%s", coinbaseproOrders, orderID)
|
|
|
|
return c.SendAuthenticatedHTTPRequest(http.MethodDelete, path, nil, nil)
|
|
}
|
|
|
|
// CancelAllExistingOrders cancels all open orders on the exchange and returns
|
|
// and array of order IDs
|
|
// currencyPair - [optional] all orders for a currencyPair string will be
|
|
// canceled
|
|
func (c *CoinbasePro) CancelAllExistingOrders(currencyPair string) ([]string, error) {
|
|
var resp []string
|
|
req := make(map[string]interface{})
|
|
|
|
if len(currencyPair) > 0 {
|
|
req["product_id"] = currencyPair
|
|
}
|
|
return resp, c.SendAuthenticatedHTTPRequest(http.MethodDelete, coinbaseproOrders, req, &resp)
|
|
}
|
|
|
|
// GetOrders lists current open orders. Only open or un-settled orders are
|
|
// returned. As soon as an order is no longer open and settled, it will no
|
|
// longer appear in the default request.
|
|
// status - can be a range of "open", "pending", "done" or "active"
|
|
// currencyPair - [optional] for example "BTC-USD"
|
|
func (c *CoinbasePro) GetOrders(status []string, currencyPair string) ([]GeneralizedOrderResponse, error) {
|
|
var resp []GeneralizedOrderResponse
|
|
params := url.Values{}
|
|
|
|
for _, individualStatus := range status {
|
|
params.Add("status", individualStatus)
|
|
}
|
|
if currencyPair != "" {
|
|
params.Set("product_id", currencyPair)
|
|
}
|
|
|
|
path := common.EncodeURLValues(c.API.Endpoints.URL+coinbaseproOrders, params)
|
|
path = common.GetURIPath(path)
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, path[1:], nil, &resp)
|
|
}
|
|
|
|
// GetOrder returns a single order by order id.
|
|
func (c *CoinbasePro) GetOrder(orderID string) (GeneralizedOrderResponse, error) {
|
|
resp := GeneralizedOrderResponse{}
|
|
path := fmt.Sprintf("%s/%s", coinbaseproOrders, orderID)
|
|
|
|
return resp, c.SendAuthenticatedHTTPRequest(http.MethodGet, path, nil, &resp)
|
|
}
|
|
|
|
// GetFills returns a list of recent fills
|
|
func (c *CoinbasePro) GetFills(orderID, currencyPair string) ([]FillResponse, error) {
|
|
var resp []FillResponse
|
|
params := url.Values{}
|
|
|
|
if orderID != "" {
|
|
params.Set("order_id", orderID)
|
|
}
|
|
if currencyPair != "" {
|
|
params.Set("product_id", currencyPair)
|
|
}
|
|
if params.Get("order_id") == "" && params.Get("product_id") == "" {
|
|
return resp, errors.New("no parameters set")
|
|
}
|
|
|
|
path := common.EncodeURLValues(c.API.Endpoints.URL+coinbaseproFills, params)
|
|
uri := common.GetURIPath(path)
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, uri[1:], nil, &resp)
|
|
}
|
|
|
|
// MarginTransfer sends funds between a standard/default profile and a margin
|
|
// profile.
|
|
// A deposit will transfer funds from the default profile into the margin
|
|
// profile. A withdraw will transfer funds from the margin profile to the
|
|
// default profile. Withdraws will fail if they would set your margin ratio
|
|
// below the initial margin ratio requirement.
|
|
//
|
|
// amount - the amount to transfer between the default and margin profile
|
|
// transferType - either "deposit" or "withdraw"
|
|
// profileID - The id of the margin profile to deposit or withdraw from
|
|
// currency - currency to transfer, currently on "BTC" or "USD"
|
|
func (c *CoinbasePro) MarginTransfer(amount float64, transferType, profileID, currency string) (MarginTransfer, error) {
|
|
resp := MarginTransfer{}
|
|
req := make(map[string]interface{})
|
|
req["type"] = transferType
|
|
req["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
|
|
req["currency"] = currency
|
|
req["margin_profile_id"] = profileID
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproMarginTransfer, req, &resp)
|
|
}
|
|
|
|
// GetPosition returns an overview of account profile.
|
|
func (c *CoinbasePro) GetPosition() (AccountOverview, error) {
|
|
resp := AccountOverview{}
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, coinbaseproPosition, nil, &resp)
|
|
}
|
|
|
|
// ClosePosition closes a position and allowing you to repay position as well
|
|
// repayOnly - allows the position to be repaid
|
|
func (c *CoinbasePro) ClosePosition(repayOnly bool) (AccountOverview, error) {
|
|
resp := AccountOverview{}
|
|
req := make(map[string]interface{})
|
|
req["repay_only"] = repayOnly
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproPositionClose, req, &resp)
|
|
}
|
|
|
|
// GetPayMethods returns a full list of payment methods
|
|
func (c *CoinbasePro) GetPayMethods() ([]PaymentMethod, error) {
|
|
var resp []PaymentMethod
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, coinbaseproPaymentMethod, nil, &resp)
|
|
}
|
|
|
|
// DepositViaPaymentMethod deposits funds from a payment method. See the Payment
|
|
// Methods section for retrieving your payment methods.
|
|
//
|
|
// amount - The amount to deposit
|
|
// currency - The type of currency
|
|
// paymentID - ID of the payment method
|
|
func (c *CoinbasePro) DepositViaPaymentMethod(amount float64, currency, paymentID string) (DepositWithdrawalInfo, error) {
|
|
resp := DepositWithdrawalInfo{}
|
|
req := make(map[string]interface{})
|
|
req["amount"] = amount
|
|
req["currency"] = currency
|
|
req["payment_method_id"] = paymentID
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproPaymentMethodDeposit, req, &resp)
|
|
}
|
|
|
|
// DepositViaCoinbase deposits funds from a coinbase account. Move funds between
|
|
// a Coinbase account and coinbasepro trading account within daily limits. Moving
|
|
// funds between Coinbase and coinbasepro is instant and free. See the Coinbase
|
|
// Accounts section for retrieving your Coinbase accounts.
|
|
//
|
|
// amount - The amount to deposit
|
|
// currency - The type of currency
|
|
// accountID - ID of the coinbase account
|
|
func (c *CoinbasePro) DepositViaCoinbase(amount float64, currency, accountID string) (DepositWithdrawalInfo, error) {
|
|
resp := DepositWithdrawalInfo{}
|
|
req := make(map[string]interface{})
|
|
req["amount"] = amount
|
|
req["currency"] = currency
|
|
req["coinbase_account_id"] = accountID
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproDepositCoinbase, req, &resp)
|
|
}
|
|
|
|
// WithdrawViaPaymentMethod withdraws funds to a payment method
|
|
//
|
|
// amount - The amount to withdraw
|
|
// currency - The type of currency
|
|
// paymentID - ID of the payment method
|
|
func (c *CoinbasePro) WithdrawViaPaymentMethod(amount float64, currency, paymentID string) (DepositWithdrawalInfo, error) {
|
|
resp := DepositWithdrawalInfo{}
|
|
req := make(map[string]interface{})
|
|
req["amount"] = amount
|
|
req["currency"] = currency
|
|
req["payment_method_id"] = paymentID
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproWithdrawalPaymentMethod, req, &resp)
|
|
}
|
|
|
|
// /////////////////////// NO ROUTE FOUND ERROR ////////////////////////////////
|
|
// WithdrawViaCoinbase withdraws funds to a coinbase account.
|
|
//
|
|
// amount - The amount to withdraw
|
|
// currency - The type of currency
|
|
// accountID - ID of the coinbase account
|
|
// func (c *CoinbasePro) WithdrawViaCoinbase(amount float64, currency, accountID string) (DepositWithdrawalInfo, error) {
|
|
// resp := DepositWithdrawalInfo{}
|
|
// req := make(map[string]interface{})
|
|
// req["amount"] = amount
|
|
// req["currency"] = currency
|
|
// req["coinbase_account_id"] = accountID
|
|
//
|
|
// return resp,
|
|
// c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproWithdrawalCoinbase, req, &resp)
|
|
// }
|
|
|
|
// WithdrawCrypto withdraws funds to a crypto address
|
|
//
|
|
// amount - The amount to withdraw
|
|
// currency - The type of currency
|
|
// cryptoAddress - A crypto address of the recipient
|
|
func (c *CoinbasePro) WithdrawCrypto(amount float64, currency, cryptoAddress string) (DepositWithdrawalInfo, error) {
|
|
resp := DepositWithdrawalInfo{}
|
|
req := make(map[string]interface{})
|
|
req["amount"] = amount
|
|
req["currency"] = currency
|
|
req["crypto_address"] = cryptoAddress
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproWithdrawalCrypto, req, &resp)
|
|
}
|
|
|
|
// GetCoinbaseAccounts returns a list of coinbase accounts
|
|
func (c *CoinbasePro) GetCoinbaseAccounts() ([]CoinbaseAccounts, error) {
|
|
var resp []CoinbaseAccounts
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, coinbaseproCoinbaseAccounts, nil, &resp)
|
|
}
|
|
|
|
// GetReport returns batches of historic information about your account in
|
|
// various human and machine readable forms.
|
|
//
|
|
// reportType - "fills" or "account"
|
|
// startDate - Starting date for the report (inclusive)
|
|
// endDate - Ending date for the report (inclusive)
|
|
// currencyPair - ID of the product to generate a fills report for.
|
|
// E.c. BTC-USD. *Required* if type is fills
|
|
// accountID - ID of the account to generate an account report for. *Required*
|
|
// if type is account
|
|
// format - pdf or csv (default is pdf)
|
|
// email - [optional] Email address to send the report to
|
|
func (c *CoinbasePro) GetReport(reportType, startDate, endDate, currencyPair, accountID, format, email string) (Report, error) {
|
|
resp := Report{}
|
|
req := make(map[string]interface{})
|
|
req["type"] = reportType
|
|
req["start_date"] = startDate
|
|
req["end_date"] = endDate
|
|
req["format"] = "pdf"
|
|
|
|
if currencyPair != "" {
|
|
req["product_id"] = currencyPair
|
|
}
|
|
if accountID != "" {
|
|
req["account_id"] = accountID
|
|
}
|
|
if format == "csv" {
|
|
req["format"] = format
|
|
}
|
|
if email != "" {
|
|
req["email"] = email
|
|
}
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodPost, coinbaseproReports, req, &resp)
|
|
}
|
|
|
|
// GetReportStatus once a report request has been accepted for processing, the
|
|
// status is available by polling the report resource endpoint.
|
|
func (c *CoinbasePro) GetReportStatus(reportID string) (Report, error) {
|
|
resp := Report{}
|
|
path := fmt.Sprintf("%s/%s", coinbaseproReports, reportID)
|
|
|
|
return resp, c.SendAuthenticatedHTTPRequest(http.MethodGet, path, nil, &resp)
|
|
}
|
|
|
|
// GetTrailingVolume this request will return your 30-day trailing volume for
|
|
// all products.
|
|
func (c *CoinbasePro) GetTrailingVolume() ([]Volume, error) {
|
|
var resp []Volume
|
|
|
|
return resp,
|
|
c.SendAuthenticatedHTTPRequest(http.MethodGet, coinbaseproTrailingVolume, nil, &resp)
|
|
}
|
|
|
|
// SendHTTPRequest sends an unauthenticated HTTP request
|
|
func (c *CoinbasePro) SendHTTPRequest(path string, result interface{}) error {
|
|
return c.SendPayload(context.Background(), &request.Item{
|
|
Method: http.MethodGet,
|
|
Path: path,
|
|
Result: result,
|
|
Verbose: c.Verbose,
|
|
HTTPDebugging: c.HTTPDebugging,
|
|
HTTPRecording: c.HTTPRecording,
|
|
})
|
|
}
|
|
|
|
// SendAuthenticatedHTTPRequest sends an authenticated HTTP request
|
|
func (c *CoinbasePro) SendAuthenticatedHTTPRequest(method, path string, params map[string]interface{}, result interface{}) (err error) {
|
|
if !c.AllowAuthenticatedRequest() {
|
|
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
|
|
c.Name)
|
|
}
|
|
|
|
payload := []byte("")
|
|
|
|
if params != nil {
|
|
payload, err = json.Marshal(params)
|
|
if err != nil {
|
|
return errors.New("sendAuthenticatedHTTPRequest: Unable to JSON request")
|
|
}
|
|
|
|
if c.Verbose {
|
|
log.Debugf(log.ExchangeSys, "Request JSON: %s\n", payload)
|
|
}
|
|
}
|
|
|
|
now := time.Now()
|
|
n := strconv.FormatInt(now.Unix(), 10)
|
|
message := n + method + "/" + path + string(payload)
|
|
hmac := crypto.GetHMAC(crypto.HashSHA256, []byte(message), []byte(c.API.Credentials.Secret))
|
|
headers := make(map[string]string)
|
|
headers["CB-ACCESS-SIGN"] = crypto.Base64Encode(hmac)
|
|
headers["CB-ACCESS-TIMESTAMP"] = n
|
|
headers["CB-ACCESS-KEY"] = c.API.Credentials.Key
|
|
headers["CB-ACCESS-PASSPHRASE"] = c.API.Credentials.ClientID
|
|
headers["Content-Type"] = "application/json"
|
|
|
|
// Timestamp must be within 30 seconds of the api service time
|
|
ctx, cancel := context.WithDeadline(context.Background(), now.Add(30*time.Second))
|
|
defer cancel()
|
|
return c.SendPayload(ctx, &request.Item{
|
|
Method: method,
|
|
Path: c.API.Endpoints.URL + path,
|
|
Headers: headers,
|
|
Body: bytes.NewBuffer(payload),
|
|
Result: result,
|
|
AuthRequest: true,
|
|
Verbose: c.Verbose,
|
|
HTTPDebugging: c.HTTPDebugging,
|
|
HTTPRecording: c.HTTPRecording,
|
|
})
|
|
}
|
|
|
|
// GetFee returns an estimate of fee based on type of transaction
|
|
func (c *CoinbasePro) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
|
|
var fee float64
|
|
switch feeBuilder.FeeType {
|
|
case exchange.CryptocurrencyTradeFee:
|
|
trailingVolume, err := c.GetTrailingVolume()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
fee = c.calculateTradingFee(trailingVolume,
|
|
feeBuilder.Pair.Base,
|
|
feeBuilder.Pair.Quote,
|
|
feeBuilder.Pair.Delimiter,
|
|
feeBuilder.PurchasePrice,
|
|
feeBuilder.Amount,
|
|
feeBuilder.IsMaker)
|
|
case exchange.InternationalBankWithdrawalFee:
|
|
fee = getInternationalBankWithdrawalFee(feeBuilder.FiatCurrency)
|
|
case exchange.InternationalBankDepositFee:
|
|
fee = getInternationalBankDepositFee(feeBuilder.FiatCurrency)
|
|
case exchange.OfflineTradeFee:
|
|
fee = getOfflineTradeFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
|
|
}
|
|
|
|
if fee < 0 {
|
|
fee = 0
|
|
}
|
|
|
|
return fee, nil
|
|
}
|
|
|
|
// getOfflineTradeFee calculates the worst case-scenario trading fee
|
|
func getOfflineTradeFee(price, amount float64) float64 {
|
|
return 0.0025 * price * amount
|
|
}
|
|
|
|
func (c *CoinbasePro) calculateTradingFee(trailingVolume []Volume, base, quote currency.Code, delimiter string, purchasePrice, amount float64, isMaker bool) float64 {
|
|
var fee float64
|
|
for _, i := range trailingVolume {
|
|
if strings.EqualFold(i.ProductID, base.String()+delimiter+quote.String()) {
|
|
switch {
|
|
case isMaker:
|
|
fee = 0
|
|
case i.Volume <= 10000000:
|
|
fee = 0.003
|
|
case i.Volume > 10000000 && i.Volume <= 100000000:
|
|
fee = 0.002
|
|
case i.Volume > 100000000:
|
|
fee = 0.001
|
|
}
|
|
break
|
|
}
|
|
}
|
|
return fee * amount * purchasePrice
|
|
}
|
|
|
|
func getInternationalBankWithdrawalFee(c currency.Code) float64 {
|
|
var fee float64
|
|
|
|
if c == currency.USD {
|
|
fee = 25
|
|
} else if c == currency.EUR {
|
|
fee = 0.15
|
|
}
|
|
|
|
return fee
|
|
}
|
|
|
|
func getInternationalBankDepositFee(c currency.Code) float64 {
|
|
var fee float64
|
|
|
|
if c == currency.USD {
|
|
fee = 10
|
|
} else if c == currency.EUR {
|
|
fee = 0.15
|
|
}
|
|
|
|
return fee
|
|
}
|