coinbasetrade

package module
v0.0.0-...-4f458e1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2023 License: MIT Imports: 16 Imported by: 0

README

go-coinbase-trade

Go library for the Coinbase Advanced Trade REST API

Reference: https://docs.cloud.coinbase.com/advanced-trade-api/docs/rest-api-overview

With the move from Coinbase Pro, Coinbase's trading API has been merged with the API for Coinbase's wallet functionality. This library only supports the Advanced Trade API, which includes the following methods:

  • List Accounts - Get a list of all accounts (wallets)
  • Get Account - Get details for one account
  • Create Order - Place a new order on the exchange
  • Cancel Orders - Cancel one or more orders that have already been placed
  • List Orders - Get a list of all orders that meet the specified criteria
  • List Fills - Get a list of all fills (matches) that meet the specified criteria
  • Get Order - Get details for one order
  • List Products - Get a list of all products (trading pairs)
  • Get Product - Get details for one product
  • Get Product Candles - Get historical market data for one product
  • Get Market Trades - Get the latest trades for one product

Access to the order book will be added later, as it uses a socket instead of REST.

Credentials

To use this library, you will need to initalize a client with the API key and secret provided by your Coinbase account. The Host and Path values only need to be provided if you want to use something other than the production server (e.g. sandbox testing, etc)

There are two ways to provide your credentials when creating a client:

Set the following environment variables in your OS:

  • COINBASE_KEY - Your API key
  • COINBASE_SECRET - Your API secret
  • COINBASE_HOST (Optional) - Use a host other than https://coinbase.com
  • COINBASE_PATH (Optional) - Use a path other than /api/v3/brokerage

You can now create a client within your project without needing to specify any parameters:

client := coinbasetrade.NewClient(nil)
Pass credentials in code

You can also populate a configuration object containing your credentials and include it when creating your client:

config := coinbasetrade.ClientConfig{
  Key: [your api key],
  Secret: [your api secret],
  Host: [optional host],
  Path: [optional path],
}

client := coinbasetrade.NewClient(&config)

Numbers

All numbers related to monetary value or volume of orders use the Shopspring decimal library. Although the Coinbase API deals in strings, coinbase-trade will automatically convert numerical values to and from decimal.Decimal objects for use within your project. This keeps floating-point arithmetic precise and easy to manage.

Lists

Calling any of the above methods that have List in their name will return an object prepopulated with the first page of results. Every list object will have a Next() function which will return true as long as there is still data to be consumed. Call NextPage() to update the object with the next set of data. To consume all data, continue calling NextPage() until Next() returns false:

list := client.ListAccounts()
for ; list.Next(); list.NextPage() {
  for i, v := range list.Accounts {
    // This loop will interate through all accounts
  }
}

Orders

Orders store the product (trading pair) and side (buy or sell) for the order. They then use an OrderConfiguration object to specify the remaining, optional details of the order (purchase price, size, expiration date, etc). These details will determine what type of order it is: Market, Limit (GTC/GTD), or Stop Loss (GTC/GTD).

order, _ := client.GetOrder(orderID)

switch order.OrderConfiguration.Type {
  case coinbasetrade.LimitGTC:
    // This is a limit order with no expiration time
    price := config.LimitPrice
  case coinbasetrade.LimitGTD:
    // This is a limit order with an `EndTime` value
  ...
}
Placing a new order

When placing a new order, it is recommended to use one of the helper functions which will ensure you submit the correct information for each order type. Every order requires a unique "client order id", however you can pass an empty string for this value and the library will use the current unix time in milliseconds as the order id.

Placing an order with one of the Place... functions or the raw CreatOrder function will return an order object which you can later use to retrieve the updated details of the order. All of these functions will also return two error objects: the first represents an error returned by the Coinbase API (malformed request, unauthorized, etc), and the second represents an error at the networking level (server unavailable, etc).

// Buy $1,000 worth of Bitcoin with a market order
placedOrder, apierror, err := client.PlaceMarketIOC("", "BTC-USD", coinbasetrade.Buy, decimal.NewFromFloat(1000))
Updating the status of an order

To refresh the status of placedOrder, you can either pass it to the client to be updated in place:

err = client.UpdateOrder(placedOrder)

Or retrieve the order again, using the order id:

updatedOrder, err := client.GetOrder(placedOrder.ID)

More information

If any details are lacking in this documentation, please open a new issue and I will be happy to elaborate.

Documentation

Index

Constants

View Source
const (
	Buy         Side = "BUY"
	Sell        Side = "SELL"
	UnknownSide      = "UNKNOWN_ORDER_SIDE"

	Pending       OrderStatus = "PENDING"
	Open          OrderStatus = "OPEN"
	Filled        OrderStatus = "FILLED"
	Cancelled     OrderStatus = "CANCELLED"
	Expired       OrderStatus = "EXPIRED"
	Failed        OrderStatus = "FAILED"
	UnknownStatus OrderStatus = "UNKNOWN_ORDER_STATUS"

	GoodUntilDateTime  TimeInForce = "GOOD_UNTIL_DATE_TIME"
	GoodUntilCancelled TimeInForce = "GOOD_UNTIL_CANCELLED"
	ImmediateOrCancel  TimeInForce = "IMMEDIATE_OR_CANCEL"
	FillOrKill         TimeInForce = "FILL_OR_KILL"
	UnknownTimeInForce TimeInForce = "UNKNOWN_TIME_IN_FORCE"

	InvalidOrderType     TriggerStatus = "INVALID_ORDER_TYPE"
	StopPending          TriggerStatus = "STOP_PENDING"
	StopTriggered        TriggerStatus = "STOP_TRIGGERED"
	UnknownTriggerStatus TriggerStatus = "UNKNOWN_TRIGGER_STATUS"

	Market           OrderType = "MARKET"
	Limit            OrderType = "LIMIT"
	Stop             OrderType = "STOP"
	StopLimit        OrderType = "STOP_LIMIT"
	UnknownOrderType OrderType = "UNKNOWN_ORDER_TYPE"

	MarketIOC                 OrderConfigurationType = "market_market_ioc"
	LimitGTC                  OrderConfigurationType = "limit_limit_gtc"
	LimitGTD                  OrderConfigurationType = "limit_limit_gtd"
	StopLimitGTC              OrderConfigurationType = "stop_limit_stop_limit_gtc"
	StopLimitGTD              OrderConfigurationType = "stop_limit_stop_limit_gtd"
	UnknownOrderConfiguration OrderConfigurationType = "unknown_order_config_type"

	StopDirectionUp      StopDirection = "STOP_DIRECTION_STOP_UP"
	StopDirectionDown    StopDirection = "STOP_DIRECTION_STOP_DOWN"
	UnknownStopDirection StopDirection = "UNKNOWN_STOP_DIRECTION"

	UnknownFailureReason          CreateOrderError = "UNKNOWN_FAILURE_REASON"
	UnsupportedOrderConfiguration CreateOrderError = "UNSUPPORTED_ORDER_CONFIGURATION"
	InvalidSide                   CreateOrderError = "INVALID_SIDE"
	InvalidProductId              CreateOrderError = "INVALID_PRODUCT_ID"
	InvalidSizePrecision          CreateOrderError = "INVALID_SIZE_PRECISION"
	InvalidPricePrecision         CreateOrderError = "INVALID_PRICE_PRECISION"
	InsufficientFund              CreateOrderError = "INSUFFICIENT_FUND"
	InvalidLedgerBalance          CreateOrderError = "INVALID_LEDGER_BALANCE"
	OrderEntryDisabled            CreateOrderError = "ORDER_ENTRY_DISABLED"
	IneligiblePair                CreateOrderError = "INELIGIBLE_PAIR"
	InvalidLimitPricePostOnly     CreateOrderError = "INVALID_LIMIT_PRICE_POST_ONLY"
	InvalidLimitPrice             CreateOrderError = "INVALID_LIMIT_PRICE"
	InvalidNoLiquidity            CreateOrderError = "INVALID_NO_LIQUIDITY"
	InvalidRequest                CreateOrderError = "INVALID_REQUEST"
	CommanderRejectedNewOrder     CreateOrderError = "COMMANDER_REJECTED_NEW_ORDER"
	InsufficientFunds             CreateOrderError = "INSUFFICIENT_FUNDS"

	UnknownCancelFailureReason   CancelOrderError = "UNKNOWN_CANCEL_FAILURE_REASON"
	InvalidCancelRequest         CancelOrderError = "INVALID_CANCEL_REQUEST"
	UnknownCancelOrder           CancelOrderError = "UNKNOWN_CANCEL_ORDER"
	CommanderRejectedCancelOrder CancelOrderError = "COMMANDER_REJECTED_CANCEL_ORDER"
	DuplicateCancelRequest       CancelOrderError = "DUPLICATE_CANCEL_REQUEST"

	TradeFill       = "FILL"
	TradeReversal   = "REVERSAL"
	TradeCorrection = "CORRECTION"
	TradeSynthetic  = "SYNTHETIC"

	LiquidityMaker   = "MAKER"
	LiquidityTaker   = "TAKER"
	LiquidityUnknown = "UNKNOWN_LIQUIDITY_INDICATOR"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	ID               string    `json:"uuid"`
	Name             string    `json:"name"`
	Currency         string    `json:"currency"`
	AvailableBalance Balance   `json:"available_balance"`
	Default          bool      `json:"default"`
	Active           bool      `json:"active"`
	CreatedAt        time.Time `json:"created_at"`
	UpdatedAt        time.Time `json:"updated_at"`
	DeletedAt        time.Time `json:"deleted_at"`
	Type             string    `json:"type"`
	Ready            bool      `json:"ready"`
	HoldBalance      Balance   `json:"hold"`
}

type AccountList

type AccountList struct {
	Accounts []Account `json:"accounts"`
	Pagination
}

type Balance

type Balance struct {
	Value    decimal.Decimal `json:"value"`
	Currency string          `json:"currency"`
}

type CancelOrderError

type CancelOrderError string

type Candle

type Candle struct {
	StartString string `json:"start"`
	StartTime   time.Time
	StartUnix   int64

	Low    decimal.Decimal `json:"low"`
	High   decimal.Decimal `json:"high"`
	Open   decimal.Decimal `json:"open"`
	Close  decimal.Decimal `json:"close"`
	Volume decimal.Decimal `json:"volume"`
}

type Client

type Client struct {
	Host   string // i.e. coinbase.com
	Path   string // path to the api
	Key    string // API key as provided by Coinbase
	Secret string // API secret as provided by Coinbase
	// contains filtered or unexported fields
}

func NewClient

func NewClient(config *ClientConfig) *Client

func (*Client) CancelOrders

func (c *Client) CancelOrders(orderIds []string) (cancelErrors map[string]CancelOrderError, err error)

CancelOrders takes a slice of order ids to cancel, and returns a map of potential errors for each order id.

func (*Client) CreateOrder

func (c *Client) CreateOrder(clientOrderId string, productId string, side Side, orderConfig OrderConfiguration) (order Order, errorType CreateOrderError, err error)

CreateOrder will submit your raw order details and return a populated `Order` object. You must include a valid `OrderConfiguration` based on the type of order you wish to place. If the combination of data populated in the order config is invalid, the server will return an error. It is recommended to use one of the helper functions instead (PlaceMarketIOC, PlaceLimitGTC, etc)

func (*Client) EnableDebug

func (c *Client) EnableDebug()

EnableDebug turns on some extra logging information

func (*Client) GetAccount

func (c *Client) GetAccount(id string) (acc Account, err error)

GetAccount takes an account ID and returns an Account object.

func (*Client) GetMarketTrades

func (c *Client) GetMarketTrades(product string, n int) (market MarketTrades, err error)

GetMarketTrades will return the current best bid and ask, plus a slice of the last `n` trades from the ticker

func (*Client) GetOrder

func (c *Client) GetOrder(id string) (o Order, err error)

GetOrder takes the order id assigned by Coinbase and returns a populated `Order` object containing the latest details from the server.

func (*Client) GetProduct

func (c *Client) GetProduct(id string) (prod Product, err error)

GetProduct takes a product ID and returns a Product object.

func (*Client) GetProductCandles

func (c *Client) GetProductCandles(id string, start, end time.Time, granularity Granularity) (candles []Candle, err error)

GetProductCandles takes a product ID, start and end times for the period you want to see, and the granularity of data that should be returned. The start time for each interval is included in 3 formats for convenience: string, int64, and time.Time.

func (*Client) ListAccounts

func (c *Client) ListAccounts(params ListAccountsParameters) (l AccountList, err error)

ListAccounts takes parameters (ListAccountsParameters), and returns an AccountsList. The AccountsList starts out popualated with the first page of results, and the next page of results can be retrieved by calling NextPage(). Next() will show if there are more pages to be retrieved.

func (*Client) ListFills

func (c *Client) ListFills(params ListFillsParameters) (l FillList, err error)

ListFills returns a list of fills based on the parameters you include.

func (*Client) ListOrders

func (c *Client) ListOrders(params ListOrdersParameters) (l OrderList, err error)

ListOrders returns a list of orders based on the parameters you include.

func (*Client) ListProducts

func (c *Client) ListProducts(params ListProductsParameters) (l ProductList, err error)

ListProducts returns a list of products based on the parameters you provide.

func (*Client) PlaceLimitGTC

func (c *Client) PlaceLimitGTC(clientOrderId string, productId string, side Side, size decimal.Decimal, price decimal.Decimal, postOnly bool) (order Order, errorType CreateOrderError, err error)

PlaceLimitGTC is a helper function to place a limit "good till closed" order. If you want to place a "post only" order, set postOnly to true.

func (*Client) PlaceLimitGTD

func (c *Client) PlaceLimitGTD(clientOrderId string, productId string, side Side, size decimal.Decimal, price decimal.Decimal, endTime time.Time, postOnly bool) (order Order, errorType CreateOrderError, err error)

PlaceLimitGTD is a helper function to place a limit "good till date" order. If you want to place a "post only" order, set postOnly to true.

func (*Client) PlaceMarketIOC

func (c *Client) PlaceMarketIOC(clientOrderId string, productId string, side Side, size decimal.Decimal) (order Order, errorType CreateOrderError, err error)

PlaceMarketIOC is a helper function to place a market "immediate or cancel" order.

func (*Client) PlaceStopLimitGTC

func (c *Client) PlaceStopLimitGTC(clientOrderId string, productId string, side Side, size decimal.Decimal, price decimal.Decimal, stopPrice decimal.Decimal, stopDirection StopDirection) (order Order, errorType CreateOrderError, err error)

PlaceStopLimitGTC is a helper function to place a limit "good till close" order with a stop loss price.

func (*Client) PlaceStopLimitGTD

func (c *Client) PlaceStopLimitGTD(clientOrderId string, productId string, side Side, size decimal.Decimal, price decimal.Decimal, stopPrice decimal.Decimal, stopDirection StopDirection, endTime time.Time) (order Order, errorType CreateOrderError, err error)

PlaceStopLimitGTD is a helper function to place a limit "good till date" order with a stop loss price.

func (*Client) UpdateOrder

func (c *Client) UpdateOrder(order *Order) (err error)

UpdateOrder takes an existing `Order` object, and updates it with the latest details from the server.

type ClientConfig

type ClientConfig struct {
	Host   string
	Path   string
	Key    string
	Secret string
}

type CreateOrderError

type CreateOrderError string

type Fill

type Fill struct {
	ID                 string             `json:"entry_id"`
	TradeID            string             `json:"trade_id"`
	OrderID            string             `json:"order_id"`
	TradeTime          time.Time          `json:"trade_time"`
	Type               TradeType          `json:"trade_type"`
	Price              decimal.Decimal    `json:"price"`
	Size               decimal.Decimal    `json:"size"`
	Commission         decimal.Decimal    `json:"commission"`
	ProductID          string             `json:"product_id"`
	SequenceTime       time.Time          `json:"sequence_timestamp"`
	LiquidityIndicator LiquidityIndicator `json:"liquidity_indicator"`
	SizeInQuote        bool               `json:"size_in_quote"`
	UserID             string             `json:"user_id"`
	Side               Side               `json:"side"`
}

type FillList

type FillList struct {
	Fills []Fill
	Pagination
}

type Granularity

type Granularity string
const (
	OneMinute     Granularity = "ONE_MINUTE"
	FiveMinute    Granularity = "FIVE_MINUTE"
	FifteenMinute Granularity = "FIFTEEN_MINUTE"
	ThirtyMinute  Granularity = "THIRTY_MINUTE"
	OneHour       Granularity = "ONE_HOUR"
	TwoHour       Granularity = "TWO_HOUR"
	SixHour       Granularity = "SIX_HOUR"
	OneDay        Granularity = "ONE_DAY"
)

type LiquidityIndicator

type LiquidityIndicator string

type ListAccountsParameters

type ListAccountsParameters struct {
	Limit int `cbt:"limit"`
}

type ListFillsParameters

type ListFillsParameters struct {
	OrderID           string    `cbt:"order_id"`
	ProductID         string    `cbt:"product_id"`
	StartSequenceTime time.Time `cbt:"start_sequence_timestamp"`
	EndSequenceTime   time.Time `cbt:"end_sequence_timestamp"`
	Limit             int       `cbt:"limit"`
}

type ListOrdersParameters

type ListOrdersParameters struct {
	Product            string        `cbt:"product_id"`
	Type               OrderType     `cbt:"order_type"`
	Side               Side          `cbt:"order_side"`
	Status             []OrderStatus `cbt:"order_status"`
	StartDate          time.Time     `cbt:"start_date"`
	EndDate            time.Time     `cbt:"end_date"`
	UserNativeCurrency string        `cbt:"user_native_currency"`
	ProductType        string        `cbt:"product_type"`
	Limit              int           `cbt:"limit"`
}

type ListProductsParameters

type ListProductsParameters struct {
	Limit int         `cbt:"limit"`
	Type  ProductType `cbt:"product_type"`
}

type MarketTrades

type MarketTrades struct {
	Trades  []Trade
	BestBid decimal.Decimal `json:"best_bid"`
	BestAsk decimal.Decimal `json:"best_ask"`
}

type Method

type Method string
const (
	Get    Method = "GET"
	Put    Method = "PUT"
	Post   Method = "POST"
	Delete Method = "DELETE"
)

type Order

type Order struct {
	// used by ListOrders
	ID                 string             `json:"order_id,omitempty"`
	Product            string             `json:"product_id"`
	UserID             string             `json:"user_id,omitempty"`
	OrderConfiguration OrderConfiguration `json:"-"`
	// OrderConfiguration   OrderConfiguration `json:"order_configuration"`
	Side                 Side            `json:"side"`
	ClientOrderID        string          `json:"client_order_id"`
	Status               string          `json:"status,omitempty"`
	TimeInForce          TimeInForce     `json:"time_in_force,omitempty"`
	CreatedTime          time.Time       `json:"created_time,omitempty"`
	CompletionPercentage decimal.Decimal `json:"completion_percentage,omitempty"`
	FilledSize           decimal.Decimal `json:"filled_size,omitempty"`
	AverageFilledPrice   decimal.Decimal `json:"average_filled_price,omitempty"`
	Fee                  string          `json:"fee,omitempty"`
	NumberOfFills        decimal.Decimal `json:"number_of_fills,omitempty"`
	FilledValue          decimal.Decimal `json:"filled_value,omitempty"`
	PendingCancel        bool            `json:"pending_cancel,omitempty"`
	SizeInQuote          bool            `json:"size_in_quote,omitempty"`
	TotalFees            decimal.Decimal `json:"total_fees,omitempty"`
	SizeInclusiveOfFees  bool            `json:"size_inclusive_of_fees,omitempty"`
	TotalValueAfterFees  decimal.Decimal `json:"total_value_after_fees,omitempty"`
	TriggerStatus        TriggerStatus   `json:"trigger_status,omitempty"`
	Type                 OrderType       `json:"order_type,omitempty"`
	RejectReason         string          `json:"reject_reason,omitempty"`
	Settled              bool            `json:"settled,omitempty"`
	ProductType          ProductType     `json:"product_type,omitempty"`
	OutstandingHold      decimal.Decimal `json:"outstanding_hold_amount"`

	// used by GetOrder
	RejectMessage string `json:"reject_message,omitempty"`
	CancelMessage string `json:"cancel_message,omitempty"`
}

Order represents the status of an order that has been placed. NOTE: As of 12/2022, "reject reason" doesn't seem to have a very obvious use, so it is left as a string for now.

type OrderConfiguration

type OrderConfiguration struct {
	Type          OrderConfigurationType `json:"-"`
	QuoteSize     decimal.Decimal        `json:"quote_size,omitempty"`
	BaseSize      decimal.Decimal        `json:"base_size,omitempty"`
	LimitPrice    decimal.Decimal        `json:"limit_price,omitempty"`
	StopPrice     decimal.Decimal        `json:"stop_price,omitempty"`
	StopDirection StopDirection          `json:"stop_direction,omitempty"`
	EndTime       time.Time              `json:"-"`
	PostOnly      bool                   `json:"post_only,omitempty"`
}

OrderConfiguration includes all the possible settings for all order types. Due to how the API works, only one value is added to the OrderConfiguration map in the Order struct above, and the key is set to the type of order. Use GetOrderConfiguration and SetOrderConfiguration instead of accesing the map directly.

type OrderConfigurationType

type OrderConfigurationType string

type OrderList

type OrderList struct {
	Orders []Order `json:"orders"`
	Pagination
}

type OrderStatus

type OrderStatus string

type OrderType

type OrderType string

type Pagination

type Pagination struct {
	// contains filtered or unexported fields
}

Pagination values need to be extracted from some API replies, but we would like to keep these values from being exposed outside this library. This struct is used for umarshaling pagination data from API responses, and then each request struct saves this information internally, in unexported fields.

func (*Pagination) Next

func (p *Pagination) Next() bool

func (*Pagination) NextPage

func (p *Pagination) NextPage() error

type Product

type Product struct {
	ID                        string          `json:"product_id"`
	Price                     decimal.Decimal `json:"price"`
	Volume24h                 decimal.Decimal `json:"volume_24h"`
	PricePercentageChange24h  string          `json:"price_percentage_change_24h"`
	VolumePercentageChange24h string          `json:"volume_percentage_change_24h"`
	BaseIncrement             decimal.Decimal `json:"base_increment"`
	QuoteIncrement            decimal.Decimal `json:"quote_increment"`
	QuoteMinSize              decimal.Decimal `json:"quote_min_size"`
	QuoteMaxSize              decimal.Decimal `json:"quote_max_size"`
	BaseMinSize               decimal.Decimal `json:"base_min_size"`
	BaseMaxSize               decimal.Decimal `json:"base_max_size"`
	BaseName                  string          `json:"base_name"`
	QuoteName                 string          `json:"quote_name"`
	Watched                   bool            `json:"watched"`
	IsDisabled                bool            `json:"is_disabled"`
	New                       bool            `json:"new"`
	Status                    string          `json:"status"`
	CancelOnly                bool            `json:"cancel_only"`
	LimitOnly                 bool            `json:"limit_only"`
	PostOnly                  bool            `json:"post_only"`
	TradingDisabled           bool            `json:"trading_disabled"`
	AuctionMode               bool            `json:"auction_mode"`
	ProductType               string          `json:"product_type"`
	QuoteCurrencyID           string          `json:"quote_currency_id"`
	BaseCurrencyID            string          `json:"base_currency_id"`
}

type ProductList

type ProductList struct {
	Products []Product `json:"products"`
	Pagination
}

type ProductType

type ProductType string
const (
	UnknownProductType ProductType = "UNKNOWN_PRODUCT_TYPE"
	ProductTypeSpot    ProductType = "SPOT"
)

type Side

type Side string

for orders

type StopDirection

type StopDirection string

type TimeInForce

type TimeInForce string

type Trade

type Trade struct {
	ID        string          `json:"trade_id"`
	ProductID string          `json:"product_id"`
	Price     decimal.Decimal `json:"price"`
	Size      decimal.Decimal `json:"size"`
	Time      time.Time       `json:"time"`
	Side      Side            `json:"side"`
}

type TradeType

type TradeType string

for fills

type TriggerStatus

type TriggerStatus string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL