godax

package
v0.0.0-...-f8c417b Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2020 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package godax implements an http client for interacting with the coinbase pro API. Rest API PUBLIC ENDPOINTS

We throttle public endpoints by IP: 3 requests per second, up to 6 requests per second in bursts.
Some endpoints may have custom rate limits.

PRIVATE ENDPOINTS

We throttle private endpoints by profile ID: 5 requests per second, up to 10 requests per second
in bursts. Some endpoints may have custom rate limits.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingOrderOrProductID = errors.New("please provide either an order_id or product_id in your query params")
	ErrMissingProductID        = errors.New("please provide a product_id in your query params")
	ErrMissingConversionParams = errors.New("please provide all of the following params: to, from, amount")
	ErrCoinbaseProAPIChange    = errors.New("there appears to have been a coinbase pro API change. Please open a new issue on godax, thanks")
	ErrMarginMethodsOnHold     = errors.New("all methods interacting with margin are on hold until I can test on the sandbox")
	ErrMissingCurrency         = errors.New("please provide the WithdrawalCurrency param")
)

ErrMissingOrderOrProductID TODO: does this feel weird and one offy right now?

Functions

This section is empty.

Types

type Account

type Account struct {
	// ID - the account ID associated with the coinbase pro profile
	ID string `json:"id"`

	// Balance - the total funds in the account
	Balance string `json:"balance"`

	// Holds - funds on hold (not available for use)
	Holds string `json:"holds"`

	// Available - funds available to withdraw or trade
	Available string `json:"available"`

	// Currency - the currency of the account
	Currency string `json:"currency"`
}

Account describes information for a single account

type AccountActivity

type AccountActivity struct {
	// ID - the account ID associated with the coinbase pro profile
	ID string `json:"id"`

	// CreatedAt - when did this activity happen
	CreatedAt string `json:"created_at"`

	// Amount - the amount used in this activity
	Amount string `json:"amount"`

	// Balance - the total funds available
	Balance string `json:"balance"`

	// Type can be one of the following:
	// "transfer"   - Funds moved to/from Coinbase to Coinbase Pro
	// "match"      - Funds moved as a result of a trade
	// "fee"        - Fee as a result of a trade
	// "rebate"     - Fee rebate as per our fee schedule
	// "conversion"	- Funds converted between fiat currency and a stablecoin/
	Type string `json:"type"`

	// Details - If an entry is the result of a trade (match, fee),
	// the details field will contain additional information about the trade.
	Details ActivityDetail `json:"details"`
}

AccountActivity represents an increase or decrease in your account balance.

type AccountHold

type AccountHold struct {
	// ID - the hold ID
	ID string `json:"id"`

	// Account ID - the account ID associated with the coinbase pro profile
	AccountID string `json:"account_id"`

	// CreatedAt - when this hold happened
	CreatedAt string `json:"created_at"`

	// Updated - the last time this hold was updated
	UpdatedAt string `json:"updated_at"`

	// Amount - the amount in the hold
	Amount string `json:"amount"`

	// Type - type of the hold will indicate why the hold exists. The hold type is order
	// for holds related to open orders and transfer for holds related to a withdraw.
	Type string `json:"type"`

	// Ref - The ref field contains the id of the order or transfer which created the hold.
	Ref string `json:"ref"`
}

AccountHold describes a hold on your coinbase pro account.

type ActivityDetail

type ActivityDetail struct {
	// OrderID - the order ID related to the activity
	OrderID string `json:"order_id"`

	// TradeID - the trade ID related to the activity
	TradeID string `json:"trade_id"`

	// ProductID - the product ID related to the activity
	ProductID string `json:"product_id"`
}

ActivityDetail describes important activity metadata (order, trade, and product IDs).

type AllWithdrawalPower

type AllWithdrawalPower struct {
	ProfileID                  string                      `json:"profile_id"`
	MarginableWithdrawalPowers []MarginableWithdrawalPower `json:"marginable_withdrawal_powers"`
}

AllWithdrawalPower represents the max amount of each currency that you can withdraw from your margin profile. Used for calls to GetAllWithdrawalPower.

type AvailableBorrowLimits

type AvailableBorrowLimits struct {
	MarginableLimit    float64 `json:"marginable_limit"`
	NonMarginableLimit float64 `json:"nonmarginable_limit"`
}

AvailableBorrowLimits describes your marginable and non-marginale limits.

type BankCountry

type BankCountry struct {
	Code string `json:"code"`
	Name string `json:"name"`
}

BankCountry represents a bank country object in a WireDepositInfo.

type BuyingPower

type BuyingPower struct {
	BuyingPower            float64 `json:"buying_power"`
	SellingPower           float64 `json:"selling_power"`
	BuyingPowerExplanation string  `json:"buying_power_explanation"`
}

BuyingPower represents a buying power and selling power for a particular product. Used for marshalling response from GetBuyingPower

type Client

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

Client is the main export of godax. All its fields are unexported. This file contains all the exported methods available to use.

func NewClient

func NewClient() (*Client, error)

NewClient returns a godax Client that is hooked up to the live REST and web socket APIs.

func NewSandboxClient

func NewSandboxClient() (*Client, error)

NewSandboxClient returns a godax Client that is hooked up to the sandbox REST and web socket APIs.

func (*Client) CancelAllOrders

func (c *Client) CancelAllOrders(qp QueryParams) (canceledOrderIDs []string, err error)

CancelAllOrders cancel all open orders from the profile that the API key belongs to. The response is a list of ids of the canceled orders. This endpoint requires the "trade" permission. The productID param is opitonal and a pointer, so you can pass nil. If you do provide the productID here, you will only cancel orders open for that specific product.

func (*Client) CancelOrderByClientOID

func (c *Client) CancelOrderByClientOID(clientOID string, qp QueryParams) (canceledOrderID string, err error)

CancelOrderByClientOID cancels a previously placed order. Order must belong to the profile that the API key belongs to. If the order had no matches during its lifetime its record may be purged. This means the order details will not be available with GetOrderByID or GetOrderByClientOID. The product ID of the order is not required so if you don't have it you can pass nil here. The request will be more performant if you include it. This endpoint requires the "trade" permission.

func (*Client) CancelOrderByID

func (c *Client) CancelOrderByID(orderID string, qp QueryParams) error

CancelOrderByID cancels a previously placed order. Order must belong to the profile that the API key belongs to. If the order had no matches during its lifetime its record may be purged. This means the order details will not be available with GetOrderByID or GetOrderByClientOID. The product ID of the order is not required so if you don't have it you can pass nil here. The request will be more performant if you include it. This endpoint requires the "trade" permission.

func (*Client) CreateReport

func (c *Client) CreateReport(report ReportParams) (ReportStatus, error)

CreateReport creates reports that provide batches of historic information about your profile in various human and machine readable forms. This endpoint requires either the "view" or "trade" permission. The report will be generated when resources are available. Report status can be queried via the /reports/:report_id endpoint. The file_url field will be available once the report has successfully been created and is available for download. Expired reports: reports are only available for download for a few days after being created. Once a report expires, the report is no longer available for download and is deleted.

func (*Client) Get24HourStatsForProduct

func (c *Client) Get24HourStatsForProduct(productID string) (DayStat, error)

Get24HourStatsForProduct gets 24 hr stats for the product. Volume is in base currency units. Open, high, low are in quote currency units.

func (*Client) GetAccount

func (c *Client) GetAccount(accountID string) (Account, error)

GetAccount retrieves information for a single account. Use this endpoint when you know the account_id. API key must belong to the same profile as the account. This endpoint requires either the "view" or "trade" permission.

func (*Client) GetAccountHistory

func (c *Client) GetAccountHistory(accountID string) ([]AccountActivity, error)

GetAccountHistory lists account activity of the API key's profile. Account activity either increases or decreases your account balance. If an entry is the result of a trade (match, fee), the details field on an AccountActivity will contain additional information about the trade. Items are paginated and sorted latest first. This endpoint requires either the "view" or "trade" permission. TODO: paginate

func (*Client) GetAccountHolds

func (c *Client) GetAccountHolds(accountID string) ([]AccountHold, error)

GetAccountHolds lists holds of an account that belong to the same profile as the API key. Holds 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. This endpoint requires either the "view" or "trade" permission. TODO: paginate

func (*Client) GetAllWithdrawalPower

func (c *Client) GetAllWithdrawalPower() ([]AllWithdrawalPower, error)

GetAllWithdrawalPower returns the max amount of each currency that you can withdraw from your margin profile. This endpoint requires either the "view" or "trade" permission.

func (*Client) GetBuyingPower

func (c *Client) GetBuyingPower(qp QueryParams) (BuyingPower, error)

GetBuyingPower gets your buying power and selling power for a particular product. For example: On BTC-USD, "buying power" refers to how much USD you can use to buy BTC, and "selling power" refers to how much BTC you can sell for USD. This endpoint requires either the "view" or "trade" permission. QUERY PARAMETERS Param Default Description product_id [required] The product ID to compute buying/selling power for.

func (*Client) GetCurrentExchangeLimits

func (c *Client) GetCurrentExchangeLimits() (ExchangeLimit, error)

GetCurrentExchangeLimits will return information on your payment method transfer limits, as well as buy/sell limits per currency.

func (*Client) GetCurrentFees

func (c *Client) GetCurrentFees() (Fees, error)

GetCurrentFees returns your current maker & taker fee rates, as well as your 30-day trailing volume. Quoted rates are subject to change.

func (*Client) GetHistoricRatesForProduct

func (c *Client) GetHistoricRatesForProduct(productID string, qp QueryParams) ([]HistoricRate, error)

GetHistoricRatesForProduct gets historic rates for a product. Rates are returned in grouped buckets based on requested granularity. Historical rate data may be incomplete. No data is published for intervals where there are no ticks. PARAMETERS Param Description start Start time in ISO 8601 end End time in ISO 8601 granularity Desired timeslice in seconds If either one of the start or end fields are not provided then both fields will be ignored. If a custom time range is not declared then one ending now is selected. The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400}. Otherwise, your request will be rejected. These values correspond to timeslices representing one minute, five minutes, fifteen minutes, one hour, six hours, and one day, respectively. If data points are readily available, your response may contain as many as 300 candles and some of those candles may precede your declared start value. The maximum number of data points for a single request is 300 candles. If your selection of start/end time and granularity will result in more than 300 data points, your request will be rejected. If you wish to retrieve fine granularity data over a larger time range, you will need to make multiple requests with new start/end ranges.

func (*Client) GetMarginExitPlan

func (c *Client) GetMarginExitPlan() (ExitPlan, error)

GetMarginExitPlan returns a liquidation strategy that can be performed to get your equity percentage back to an acceptable level (i.e. your initial equity percentage). This endpoint requires either the "view" or "trade" permission.

func (*Client) GetMarginProfile

func (c *Client) GetMarginProfile(qp QueryParams) (MarginProfile, error)

GetMarginProfile gets information about your margin profile, such as your current equity percentage. This endpoint requires either the "view" or "trade" permission. QUERY PARAMETERS Param Description product_id [required] The product ID to compute buying/selling/borrow power for.

func (*Client) GetMarginStatus

func (c *Client) GetMarginStatus() (MarginStatus, error)

GetMarginStatus returns whether margin is currently enabled. This endpoint requires either the "view" or "trade" permission.

func (*Client) GetOracle

func (c *Client) GetOracle() (Oracle, error)

GetOracle gets cryptographically signed prices ready to be posted on-chain using Open Oracle (https://github.com/compound-finance/open-oracle) smart contracts. This endpoint requires the “view” permission and is accessible by any profile’s API key.

func (*Client) GetOrderByClientOID

func (c *Client) GetOrderByClientOID(orderClientOID string) (Order, error)

GetOrderByClientOID gets an order by its client OID. This endpoint requires either the "view" or "trade" permission. Orders may be queried using either the exchange assigned id or the client assigned client_oid. If the order is canceled the response may have status code 404 if the order had no matches. Note: Open orders may change state between the request and the response depending on market conditions.

func (*Client) GetOrderByID

func (c *Client) GetOrderByID(orderID string) (Order, error)

GetOrderByID gets an order by its ID. This endpoint requires either the "view" or "trade" permission. Orders may be queried using either the exchange assigned id or the client assigned client_oid. If the order is canceled the response may have status code 404 if the order had no matches. Note: Open orders may change state between the request and the response depending on market conditions.

func (*Client) GetPositionRefreshAmounts

func (c *Client) GetPositionRefreshAmounts(qp QueryParams) (RefreshAmount, error)

GetPositionRefreshAmounts returns the amount in USD of loans that will be renewed in the next day and then the day after. "twoDayRenewalAmount" is the amount to be refreshed on only the second day. This endpoint requires either the "view" or "trade" permission.

func (*Client) GetProductByID

func (c *Client) GetProductByID(productID string) (Product, error)

GetProductByID gets market data for a specific currency pair.

func (*Client) GetProductOrderBook

func (c *Client) GetProductOrderBook(productID string, qp QueryParams) (OrderBook, error)

GetProductOrderBook gets a list of open orders for a product. The amount of detail shown can be customized with the level parameter. By default, only the inside (i.e. best) bid and ask are returned. This is equivalent to a book depth of 1 level. If you would like to see a larger order book, specify the level query parameter. If a level is not aggregated, then all of the orders at each price will be returned. Aggregated levels return only one size for each active price (as if there was only a single order for that size at the level). You can provide the "level" query param here which defaults to "1" if you do not specify. Level Description 1 Only the best bid and ask 2 Top 50 bids and asks (aggregated) 3 Full order book (non aggregated) This request is NOT paginated. The entire book is returned in one response. Level 1 and Level 2 are recommended for polling. For the most up-to-date data, consider using the websocket stream. Level 3 is only recommended for users wishing to maintain a full real-time order book using the websocket stream. Abuse of Level 3 via polling will cause your access to be limited or blocked.

func (*Client) GetProductTicker

func (c *Client) GetProductTicker(productID string) (Ticker, error)

GetProductTicker returns snapshot information about the last trade (tick), best bid/ask and 24h volume. Polling is discouraged in favor of connecting via the websocket stream and listening for match messages.

func (*Client) GetProfile

func (c *Client) GetProfile(profileID string) (Profile, error)

GetProfile gets a single profile by profile id. This endpoint requires the "view" permission and is accessible by any profile's API key.

func (*Client) GetReportStatus

func (c *Client) GetReportStatus(reportID string) (ReportStatus, error)

GetReportStatus Once a report request has been accepted for processing, the status is available by polling the report resource endpoint. The final report will be uploaded and available at file_url once the status indicates ready. STATUS DESCRIPTION pending The report request has been accepted and is awaiting processing creating The report is being created ready The report is ready for download from file_url This endpoint requires either the "view" or "trade" permission.

func (*Client) GetServerTime

func (c *Client) GetServerTime() (ServerTime, error)

GetServerTime fetches the current coinbase pro server time. This endpoint does not require authentication.

func (*Client) GetTrailingVolume

func (c *Client) GetTrailingVolume() ([]UserAccount, error)

GetTrailingVolume returns your 30-day trailing volume for all products of the API key's profile. This is a cached value that's calculated every day at midnight UTC. This endpoint requires either the "view" or "trade" permission.

func (*Client) GetWithdrawalPowerForCurrency

func (c *Client) GetWithdrawalPowerForCurrency(qp QueryParams) ([]CurrencyWithdrawalPower, error)

GetWithdrawalPowerForCurrency Returns the max amount of the given currency that you can withdraw from your margin profile. QUERY PARAMETERS Param Default Description currency [required] The currency to compute withdrawal power for. This endpoint requires either the "view" or "trade" permission.

func (*Client) ListAccounts

func (c *Client) ListAccounts() ([]ListAccount, error)

ListAccounts gets a list of trading accounts from the profile associated with the API key. This endpoint requires either the "view" or "trade" permission. This endpoint has a custom rate limit by profile ID: 25 requests per second, up to 50 requests per second in bursts

func (*Client) ListCoinbaseAccounts

func (c *Client) ListCoinbaseAccounts() ([]CoinbaseAccount, error)

ListCoinbaseAccounts lists your user's coinbase (non-pro) accounts. This endpoint requires either the "view" or "transfer" permission.

func (*Client) ListCurrencies

func (c *Client) ListCurrencies() ([]Currency, error)

ListCurrencies lists known currencies. Currency codes will conform to the ISO 4217 standard where possible. Currencies which have or had no representation in ISO 4217 may use a custom code. Code Description BTC Bitcoin ETH Ether LTC Litecoin

func (*Client) ListFills

func (c *Client) ListFills(qp QueryParams) ([]Fill, error)

ListFills gets a list of recent fills of the API key's profile. This endpoint requires either the "view" or "trade" permission. You can request fills for specific orders or products using the orderID and productID parameters. You are required to provide either a product_id or order_id.

Fees are recorded in two stages. Immediately after the matching engine completes a match, the fill is inserted into our datastore. Once the fill is recorded, a settlement process will settle the fill and credit both trading counterparties. The fee field indicates the fees charged for this individual fill. TODO: paginate

func (*Client) ListLiquidationHistory

func (c *Client) ListLiquidationHistory(qp QueryParams) ([]LiquidationEvent, error)

ListLiquidationHistory returns returns a list of liquidations that were performed to get your equity percentage back to an acceptable level. This endpoint requires either the "view" or "trade" permission. QUERY PARAMETERS Param Default Description after [optional] Request liquidation history after this date.

func (*Client) ListOrders

func (c *Client) ListOrders(qp QueryParams) ([]Order, error)

ListOrders lists your current open orders from the profile that the API key belongs to. 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. This endpoint requires either the "view" or "trade" permission. Valid status args to filter return orders: [open, pending, active].

Orders which are no longer resting on the order book, will be marked with the done status. There is a small window between an order being done and settled. An order is settled when all of the fills have settled and the remaining holds (if any) have been removed.

For high-volume trading it is strongly recommended that you maintain your own list of open orders and use one of the streaming market data feeds to keep it updated. You should poll the open orders endpoint once when you start trading to obtain the current state of any open orders. executed_value is the cumulative match size * price and is only present for orders placed after 2016-05-20. Open orders may change state between the request and the response depending on market conditions. TODO: paginate

func (*Client) ListPaymentMethods

func (c *Client) ListPaymentMethods() ([]PaymentMethod, error)

ListPaymentMethods gets a list of your payment methods.

func (*Client) ListProducts

func (c *Client) ListProducts() ([]Product, error)

ListProducts gets a list of available currency pairs for trading. The Market Data API is an unauthenticated set of endpoints for retrieving market data. These endpoints provide snapshots of market data.

func (*Client) ListProfiles

func (c *Client) ListProfiles() ([]Profile, error)

ListProfiles lists the api key user's profiles which are equivilant to portfolios. This endpoint requires the "view" permission and is accessible by any profile's API key.

func (*Client) ListTradesByProduct

func (c *Client) ListTradesByProduct(productID string) ([]Trade, error)

ListTradesByProduct lists the latest trades for a product. The trade side indicates the maker order side. The maker order is the order that was open on the order book. Buy side indicates a down-tick because the maker was a buy order and their order was removed. Conversely, sell side indicates an up-tick. TODO: paginate

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(order OrderParams) (Order, error)

PlaceOrder allows you to place two types of orders: limit and market. Orders can only be placed if your account has sufficient funds. Once an order is placed, your 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. This endpoint requires the "trade" permission.

func (*Client) ProfileTransfer

func (c *Client) ProfileTransfer(transfer TransferParams) error

ProfileTransfer transfers funds from API key's profile to another user owned profile. This endpoint requires the "transfer" permission.

func (*Client) StableCoinConversion

func (c *Client) StableCoinConversion(from string, to string, amount string) (Conversion, error)

StableCoinConversion creates a stablecoin conversion. One example is converting $10,000.00 USD to 10,000.00 USDC. A successful conversion will be assigned a conversion id which comes back on the Conversion as ID. The corresponding ledger entries for a conversion will reference this conversion id. Params: from: A valid currency id to: A valid currency id amount: Amount of from to convert to to

type ClosingBuffer

type ClosingBuffer struct {
	*bytes.Buffer
}

ClosingBuffer embeds a bytes.Buffer, giving it a Read method required for a Response Body ReadCloser body

func MockBody

func MockBody(b []byte) *ClosingBuffer

MockBody creates a mock body that can be added to a response.

func (ClosingBuffer) Close

func (cb ClosingBuffer) Close() (err error)

Close allows a ClosingBuffer to Close, implementing a net/http Response Body ReadCloser interface

type CoinbaseAccount

type CoinbaseAccount struct {
	ID                     string          `json:"id"`
	Name                   string          `json:"name"`
	Balance                string          `json:"balance"`
	Currency               string          `json:"currency"`
	Type                   string          `json:"type"`
	Primary                bool            `json:"primary"`
	Active                 bool            `json:"active"`
	WireDepositInformation WireDepositInfo `json:"wire_deposit_information"`
	SepaDepositInformation SepaDepositInfo `json:"sepa_deposit_information"`
	UKDepositInformation   UKDepositInfo   `json:"uk_deposit_information"`

	// These came back on response, but were not in docs, possibly notify coinbase to update
	HoldBalance         string `json:"hold_balance"`
	HoldCurrency        string `json:"hold_currency"`
	AvailableOnConsumer bool   `json:"available_on_consumer"`
}

CoinbaseAccount represents a Coinbase (non-pro) account.

type CoinbaseErrRes

type CoinbaseErrRes struct {
	// Message contains the error information from coinbase
	Message string `json:"message"`
}

CoinbaseErrRes represents the shape that comes back when a status code is non-200

type CommonOrderParams

type CommonOrderParams struct {
	// Side is either buy or sell
	Side string `json:"side"`

	// ProductID must be a valid product id. The list of products is available via the GetProducts method.
	ProductID string `json:"product_id"`

	// ClientOID - [optional] order UUID generated by you to identify your order
	ClientOID string `json:"client_oid,omitempty"`

	// Type - [optional] limit or market. If type is not specified, the order will default to a limit order.
	Type string `json:"type,omitempty"`

	// Price - The price must be specified in quote_increment product units. The quote increment is the
	// smallest unit of price. For example, the BTC-USD product has a quote increment of 0.01 or 1 penny.
	// Prices less than 1 penny will not be accepted, and no fractional penny prices will be accepted.
	// Not required for market orders.
	Price string `json:"price"`

	// Size indicates the amount of BTC (or base currency) to buy or sell. If you are placing a market order
	// this is optional, although you will need either Size OR Funds for a market order. This is required
	// for a limit order. The size must be greater than the base_min_size for the product and no larger
	// than the base_max_size. The size can be in incremented in units of base_increment.
	Size string `json:"size,omitempty"`

	// Stp - [optional] self-trade prevention flag
	Stp string `json:"stp,omitempty"`

	// Stop - [optional] either loss or entry. Requires stop_price to be defined.
	Stop string `json:"stop,omitempty"`

	// StopPrice - [optional] Only if stop is defined. Sets trigger price for stop order.
	StopPrice string `json:"stop_price,omitempty"`
}

CommonOrderParams represent the params that both limit and market orders share.

type Conversion

type Conversion struct {
	ID            string `json:"id"`
	Amount        string `json:"amount"`
	FromAccountID string `json:"from_account_id"`
	ToAccountID   string `json:"to_account_id"`
	From          string `json:"from"`
	To            string `json:"to"`
}

Conversion represents the return value value from a call to StableCoinConversion. It describes different metadata around the stablecoin conversion.

type Currency

type Currency struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	MinSize string `json:"min_size"`
}

Currency represents an available currency on coinbase pro.

type CurrencyWithdrawalPower

type CurrencyWithdrawalPower struct {
	ProfileID       string `json:"profile_id"`
	WithdrawalPower string `json:"withdrawal_power"`
}

CurrencyWithdrawalPower represents the withdrawal power for a specific currency

type DayStat

type DayStat struct {
	Open        string `json:"open"`
	High        string `json:"high"`
	Low         string `json:"low"`
	Volume      string `json:"volume"`
	Last        string `json:"last"`
	Volume30Day string `json:"volume_30day"`
}

DayStat represents a 24 hour statistic for a product.

type ExchangeLimit

type ExchangeLimit struct {
	LimitCurrency  string         `json:"limit_currency"`
	TransferLimits TransferLimits `json:"transfer_limits"`
}

ExchangeLimit represents info about your payment method transfer limits, as well as buy/sell limits per currency.

type ExitPlan

type ExitPlan struct {
	ID                  string            `json:"id"`
	UserID              string            `json:"userId"`
	ProfileID           string            `json:"profileId"`
	AccountsList        []ExitPlanAccount `json:"accountsList"`
	EquityPercentage    string            `json:"equityPercentage"`
	TotalAssetsUSD      string            `json:"totalAssetsUsd"`
	TotalLiabilitiesUSD string            `json:"totalLiabilitiesUsd"`
	StrategiesList      []ExitStrategy    `json:"strategiesList"`
	CreatedAt           string            `json:"createdAt"`
}

ExitPlan represents a liquidation strategy that can be performed to get your equity percentage back to an acceptable level

type ExitPlanAccount

type ExitPlanAccount struct {
	ID       string `json:"id"`
	Currency string `json:"currency"`
	Amount   string `json:"amount"`
}

ExitPlanAccount represents an account within an exit plan.

type ExitStrategy

type ExitStrategy struct {
	Type      string `json:"type"`
	Amount    string `json:"amount"`
	Product   string `json:"product"`
	Strategy  string `json:"strategy"`
	AccountID string `json:"accountId"`
	OrderID   string `json:"orderId"`
}

ExitStrategy is a strategy that can be performed to get your equity percentage back to an acceptable level

type Fees

type Fees struct {
	MakerFeeRate string `json:"maker_fee_rate"`
	TakerFeeRate string `json:"taker_fee_rate"`
	USDVolume    string `json:"usd_volume"`
}

Fees represent the current maker & taker fees, and usd volume.

type Fill

type Fill struct {
	// TradeID is the identifier (int) for the trade that created the fill.
	TradeID int `json:"trade_id"`

	// ProductID - the product ID related to the activity.
	ProductID string `json:"product_id"`

	// Price is specified in quote_increment product units.
	Price string `json:"price"`

	// Size indicates the amount of BTC (or base currency) to buy or sell.
	Size string `json:"size"`

	// OrderID is the identifier (int) for the order that created the fill.
	OrderID string `json:"order_id"`

	// CreatedAt - when this fill was created.
	CreatedAt string `json:"created_at"`

	// Liquidity field indicates if the fill was the result of a liquidity provider or liquidity taker.
	// M indicates Maker and T indicates Taker
	Liquidity string `json:"liquidity"`

	// Fee indicates fees incurred as a result of the fill.
	Fee string `json:"fee"`

	// Settled indicates whether the fill has was settled yet.
	Settled bool `json:"settled"`

	// Side is either buy or sell
	Side string `json:"side"`
}

Fill represents a filled order on coinbase.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is a simple http interface that both live and test code can implement

type HistoricRate

type HistoricRate struct {
	Time   float64 `json:"time"`
	Low    float64 `json:"low"`
	High   float64 `json:"high"`
	Open   float64 `json:"open"`
	Close  float64 `json:"close"`
	Volume float64 `json:"volume"`
}

HistoricRate represents a past rate for a product.

func (*HistoricRate) UnmarshalJSON

func (h *HistoricRate) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom unmarshaller for a HistoricRate. These are returned from coinbase pro as an array of floats. We want to give them a little bit of structure.

type Limit

type Limit struct {
	// Max represents the max you can use per currency
	Max float64 `json:"max"`

	// Remaining represents your remaining amount per currency
	Remaining float64 `json:"remaining"`
}

Limit represents the actual limit metadata for a currency.

type LimitOrderParams

type LimitOrderParams struct {
	// TimeInForce - [optional] GTC, GTT, IOC, or FOK (default is GTC). Time in force policies provide
	// guarantees about the lifetime of an order. There are four policies: good till canceled GTC, good
	// till time GTT, immediate or cancel IOC, and fill or kill FOK.
	TimeInForce string `json:"time_in_force,omitempty"`

	// CancelAfter - [optional] - min, hour, day. Requires time_in_force to be GTT
	CancelAfter string `json:"cancel_after,omitempty"`

	// PostOnly - [optional] post only flag. Invalid when time_in_force is IOC or FOK.
	PostOnly bool `json:"post_only,omitempty"`
}

LimitOrderParams are embedded into OrderParams, and represent params that are only part of limit orders.

type LiqOrder

type LiqOrder struct {
	ID            string `json:"id"`
	Size          string `json:"size"`
	ProductID     string `json:"product_id"`
	ProfileID     string `json:"profile_id"`
	Side          string `json:"side"`
	Type          string `json:"type"`
	PostOnly      bool   `json:"post_only"`
	CreatedAt     string `json:"created_at"`
	DoneAt        string `json:"done_at"`
	DoneReason    string `json:"done_reason"`
	FillFees      string `json:"fill_fees"`
	FilledSize    string `json:"filled_size"`
	ExecutedValue string `json:"executed_value"`
	Status        string `json:"status"`
	Settled       bool   `json:"settled"`
}

LiqOrder is the order metadata attached to a liquidation event.

type LiquidationEvent

type LiquidationEvent struct {
	EventID   string     `json:"event_id"`
	EventTime string     `json:"event_time"`
	Orders    []LiqOrder `json:"orders"`
}

LiquidationEvent represents a liquididation event.

type ListAccount

type ListAccount struct {
	// ID - the account ID associated with the coinbase pro profile
	ID string `json:"id"`

	// Currency - the currency of the account
	Currency string `json:"currency"`

	// Balance - the total funds in the account
	Balance string `json:"balance"`

	// Available - funds available to withdraw or trade
	Available string `json:"available"`

	// Hold - funds on hold (not available for use)
	Hold string `json:"hold"`
}

ListAccount represents a trading account for a coinbase pro profile

type MarginProfile

type MarginProfile struct {
	ProfileID             string                `json:"profile_id"`
	MarginInitialEquity   string                `json:"margin_initial_equity"`
	MarginWarningEquity   string                `json:"margin_warning_equity"`
	MarginCallEquity      string                `json:"margin_call_equity"`
	EquityPercentage      float64               `json:"equity_percentage"`
	SellingPower          float64               `json:"selling_power"`
	BuyingPower           float64               `json:"buying_power"`
	BorrowPower           float64               `json:"borrow_power"`
	InterestRate          string                `json:"interest_rate"`
	InterestPaid          string                `json:"interest_paid"`
	CollateralCurrencies  []string              `json:"collateral_currencies"`
	CollateralHoldValue   string                `json:"collateral_hold_value"`
	LastLiquidationAt     string                `json:"last_liquidation_at"`
	AvailableBorrowLimits AvailableBorrowLimits `json:"available_borrow_limits"`
	BorrowLimit           string                `json:"borrow_limit"`
	TopUpAmounts          TopUpAmounts          `json:"top_up_amounts"`
}

MarginProfile represents a snapshot of a profile's margin capabilities.

type MarginStatus

type MarginStatus struct {
	Tier     int  `json:"tier"`
	Enabled  bool `json:"enabled"`
	Eligible bool `json:"eligible"`
}

MarginStatus represents the current status of an account's margin.

type MarginableWithdrawalPower

type MarginableWithdrawalPower struct {
	Currency        string `json:"currency"`
	WithdrawalPower string `json:"withdrawal_power"`
}

MarginableWithdrawalPower describes a currency and the mount of withdrawal power you have.

type MarketOrderParams

type MarketOrderParams struct {
	// Funds - [optional] desired amount of quote currency to use. When specified it indicates how much of
	// the product quote currency to buy or sell. For example, a market buy for BTC-USD with funds specified
	// as 150.00 will spend 150 USD to buy BTC (including any fees). If the funds field is not specified for
	// a market buy order, size must be specified and Coinbase Pro will use available funds in your account
	// to buy bitcoin.
	Funds string `json:"funds,omitempty"`
}

MarketOrderParams are embedded into OrderParams, and represent params that are only part of market orders. NOTE: either Size (common/shared) OR Funds in this struct must be present for a market order.

type MockClient

type MockClient struct {
	Response   []byte
	Responses  [][]byte
	Requests   []*http.Request
	StatusCode int
}

MockClient is responsible for stubbing requests in tests. If the Response field is set, the mock client will respond to each request with the Response. If Responses is set, the mock client will match subsequent requests to subsequent responses, moving along the array of Responses once for each request

func MockResponse

func MockResponse(body string) *MockClient

MockResponse creates a mock client that will return the given response on the body.

func MockResponses

func MockResponses(bodies ...string) *MockClient

MockResponses creates a mock client with a series of canned responses

func (*MockClient) Do

func (mock *MockClient) Do(req *http.Request) (*http.Response, error)

Do saves the HTTP Request, returning 200 and no error

type Oracle

type Oracle struct {
	// Timestamp indicates when the latest datapoint was obtained.
	Timestamp string `json:"timestamp"`

	// Messages array contains abi-encoded values [kind, timestamp, key, value], where kind always
	// equals to 'prices', timestamp is the time when the price was obtained, key is asset ticker
	// (e.g. 'eth') and value is asset price.
	Messages []string `json:"messages"`

	// Signatures is an array of Ethereum-compatible ECDSA signatures for each message.
	Signatures []string `json:"signatures"`

	// Prices contains human-readable asset prices.
	Prices map[string]string `json:"prices"`
}

Oracle represents cryptographically signed prices ready to be posted on-chain.

type Order

type Order struct {
	// ID is the order UUID generated by coinbase.
	ID string `json:"id"`

	// CreatedAt indicates the time the order was filled.
	CreatedAt string `json:"created_at"`

	// FillFees indicates how much in fees the order used.
	FillFees string `json:"fill_fees"`

	// FilledSize represents the order's filled amount in BTC (or base currency)
	FilledSize string `json:"filled_size"`

	// ExecutedValue indicates the value of the executed order
	ExecutedValue string `json:"executed_value"`

	// Status tells you the status of the order ("pending", "filled", etc).
	Status string `json:"status"`

	// Settled indicates whether the order has been settled yet.
	Settled bool `json:"settled"`

	// OrderParams represent all the fields available to send in a PlaceOrder call.
	// They are also attached to orders returned from coinbase after creating, listing, etc.
	OrderParams
}

Order represents a trading account for a coinbase pro profile.

type OrderBook

type OrderBook struct {
	Sequence int              `json:"sequence"`
	Bids     []OrderBookOrder `json:"bids"`
	Asks     []OrderBookOrder `json:"asks"`
}

OrderBook represents a list of orders for a product. TODO: maybe notify coinbase. The docs say sequence is a string as it appears below, however it is an int.

type OrderBookOrder

type OrderBookOrder struct {
	Price     string `json:"price"`
	Size      string `json:"size"`
	NumOrders int    `json:"num_orders"`
}

OrderBookOrder represents the price, size, and number of orders for a product.

func (*OrderBookOrder) UnmarshalJSON

func (o *OrderBookOrder) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom unmarshaller for an OrderBook. Unfortunately the coinbase pro API returns different types in the bids & asks JSON arrays, so we handle that here. This approach should provide us with all the standard JSON errors if something goes wrong.

type OrderParams

OrderParams are a combination of common/shared params as well as limit and market specific params.

type PMAmount

type PMAmount struct {
	Amount   string `json:"amount"`
	Currency string `json:"currency"`
}

PMAmount describes a currency and an amount. Used to describe a PMLimit.

type PMLimit

type PMLimit struct {
	PeriodInDays int      `json:"period_in_days"`
	Total        PMAmount `json:"total"`
	Remaining    PMAmount `json:"remaining"`
}

PMLimit represents a single payment method limit

type PMLimits

type PMLimits struct {
	Buy        []PMLimit `json:"buy"`
	InstantBuy []PMLimit `json:"instant_buy"`
	Sell       []PMLimit `json:"sell"`
	Deposit    []PMLimit `json:"deposit"`
}

PMLimits represents the available payment method limits

type Param

type Param string

Param is a type alias for a string. The hope is that godax can offer all of the available query params as constants, but also if you need to - you can create your own Param to use.

const (
	// Used in multiple queries
	OrderIDParam   Param = "order_id"
	ProductIDParam Param = "product_id"
	StatusParam    Param = "status"

	// LevelParam is used when calling GetProductOrderBook
	LevelParam Param = "level"

	// These params are used when calling GetHistoricRatesForProduct
	StartParam       Param = "start"
	EndParam         Param = "end"
	GranularityParam Param = "granularity"

	// CurrencyParam is used when calling GetWithdrawalPower
	CurrencyParam Param = "currency"
)

Available query params

type PaymentMethod

type PaymentMethod struct {
	ID            string   `json:"id"`
	Type          string   `json:"type"`
	Name          string   `json:"name"`
	Currency      string   `json:"currency"`
	PrimaryBuy    bool     `json:"primary_buy"`
	PrimarySell   bool     `json:"primary_sell"`
	AllowBuy      bool     `json:"allow_buy"`
	AllowSell     bool     `json:"allow_sell"`
	AllowDeposit  bool     `json:"allow_deposit"`
	AllowWithdraw bool     `json:"allow_withdraw"`
	Limits        PMLimits `json:"limits"`
}

PaymentMethod represents a payment method connected the the api user's account and holds metadata like type, name, currency, a list of limits, etc.

type Product

type Product struct {
	// ID represents the product ID, ie. BTC-USD
	ID string `json:"id"`

	// DisplayName represents human friendly name, example: "BTC/USD"
	DisplayName string `json:"display_name"`

	// BaseCurrency is as titled, example: "BTC"
	BaseCurrency string `json:"base_currency"`

	// BaseCurrency is as titled, example: "USD"
	QuoteCurrency string `json:"quote_currency"`

	// BaseIncrement specifies the minimum increment for the base_currency
	BaseIncrement string `json:"base_increment"`

	// QuoteIncrement specifies the min order price as well as the price increment.
	// The order price must be a multiple of this increment (i.e. if the increment is
	// 0.01, order prices of 0.001 or 0.021 would be rejected).
	QuoteIncrement string `json:"quote_increment"`

	// BaseMinSize describes the minimum order size
	BaseMinSize string `json:"base_min_size"`

	// BaseMaxSize describes the maximum order size
	BaseMaxSize string `json:"base_max_size"`

	// MinMarketFunds describes the minimum funds allowed in a market order
	MinMarketFunds string `json:"min_market_funds"`

	// MaxMarketFunds describes the maximum funds allowed in a market order
	MaxMarketFunds string `json:"max_market_funds"`

	// Status is the product's current status, example: "online"
	Status string `json:"status"`

	// StatusMessage provides any extra information regarding the status if available
	StatusMessage string `json:"status_message"`

	// CancelOnly indicates indicates whether this product only accepts cancel requests for orders
	CancelOnly bool `json:"cancel_only"`

	// LimitOnly indicates whether this product only accepts limit orders.
	// When LimitOnly is true, matching can occur if a limit order crosses the book.
	LimitOnly bool `json:"limit_only"`

	// PostOnly indicates whether only maker orders can be placed.
	// No orders will be matched when post_only mode is active
	PostOnly bool `json:"post_only"`

	// TradingDisabled indicates whether trading is currently restricted on this product.
	// This includes whether both new orders and order cancelations are restricted
	TradingDisabled bool `json:"trading_disabled"`
}

Product represents a coinbase pro product, for example "BTC-USD". Only a maximum of one of trading_disabled, cancel_only, post_only, limit_only can be true at once. If none are true, the product is trading normally. Product ID will not change once assigned to a product but all other fields ares subject to change.

type Profile

type Profile struct {
	ID        string `json:"id"`
	UserID    string `json:"user_id"`
	Name      string `json:"name"`
	Active    bool   `json:"active"`
	IsDefault bool   `json:"is_default"`
	CreatedAt string `json:"created_at"`
}

Profile represents a coinbase pro profile which is equivalent to a portfolio.

type QueryParams

type QueryParams map[Param]string

QueryParams represent the available query params for any given coinbase pro call.

type RefreshAmount

type RefreshAmount struct {
	OneDayRenewalAmount string `json:"oneDayRenewalAmount"`
	TwoDayRenewalAmount string `json:"twoDayRenewalAmount"`
}

RefreshAmount represents amount in USD of loans that will be renewed in the next day and then the day after.

type ReportParams

type ReportParams struct {
	// Type	is either "fills" or "account"
	Type string `json:"type"`

	// StartDate is the starting date for the report (inclusive)
	StartDate string `json:"start_date"`

	// EndDate is the ending date for the report (inclusive)
	EndDate string `json:"end_date"`

	// ProductID is the ID of the product to generate a fills report for.
	// E.g. BTC-USD. Required if type is fills
	ProductID string `json:"product_id,omitempty"`

	// AccountID is the ID of the account to generate an account report for. Required if type is account
	AccountID string `json:"account_id,omitempty"`

	// Format must either be "pdf" or "csv" (defualt is "pdf")
	Format string `json:"format,omitempty"`

	// Email is the email address to send the report to (optional)
	Email string `json:"email,omitempty"`
}

ReportParams describe the body needed in a call to generate a report.

type ReportStatus

type ReportStatus struct {
	ID          string       `json:"id"`
	Type        string       `json:"type"`
	Status      string       `json:"status"`
	CreatedAt   string       `json:"created_at"`
	CompletedAt string       `json:"completed_at"`
	ExpiresAt   string       `json:"expires_at"`
	FileURL     string       `json:"file_url"`
	Params      ReportParams `json:"params"`
}

ReportStatus represents the returned response after creating a report.

type SepaDepositInfo

type SepaDepositInfo struct {
	IBAN            string `json:"iban"`
	Swift           string `json:"swift"`
	BankName        string `json:"bank_name"`
	BankAddress     string `json:"bank_address"`
	BankCountryName string `json:"bank_country_name"`
	AccountName     string `json:"account_name"`
	AccountAddress  string `json:"account_address"`
	Reference       string `json:"reference"`
}

SepaDepositInfo describes all the metadata needed for a Sepa desposit.

type ServerTime

type ServerTime struct {
	ISO   string  `json:"iso"`
	Epoch float64 `json:"epoch"`
}

ServerTime represents a coinbase pro server time by providing ISO and epoch times.

type Ticker

type Ticker struct {
	TradeID int    `json:"trade_id"`
	Price   string `json:"price"`
	Size    string `json:"size"`
	Bid     string `json:"bid"`
	Ask     string `json:"ask"`
	Volume  string `json:"volume"`
	Time    string `json:"time"`
}

Ticker represents a snapshot of a trade (tick), best bid/ask and 24h volume.

type TopUpAmounts

type TopUpAmounts struct {
	BorrowableUsd    string `json:"borrowable_usd"`
	NonBorrowableUsd string `json:"non_borrowable_usd"`
}

TopUpAmounts shows borrowable and non-borrowable usd amounts.

type Trade

type Trade struct {
	Time    string `json:"time"`
	TradeID int    `json:"trade_id"`
	Price   string `json:"price"`
	Size    string `json:"size"`
	Side    string `json:"side"`
}

Trade represents a trade that has happened for a product

type TransferLimits

type TransferLimits struct {
	Ach                  map[string]Limit `json:"ach"`
	AchNoBalance         map[string]Limit `json:"ach_no_balance"`
	CreditDebitCard      map[string]Limit `json:"credit_debit_card"`
	AchCurm              map[string]Limit `json:"ach_curm"`
	Secure3DBuy          map[string]Limit `json:"secure3d_buy"`
	ExchangeWithdraw     map[string]Limit `json:"exchange_withdraw"`
	ExchangeAch          map[string]Limit `json:"exchange_ach"`
	PaypalWithdrawal     map[string]Limit `json:"paypal_withdrawal"`
	InstantAchWithdrawal map[string]Limit `json:"instant_ach_withdrawal"`
	Buy                  map[string]Limit `json:"buy"`
	Sell                 map[string]Limit `json:"sell"`
}

TransferLimits represents info about your payment method transfer limits, as well as buy/sell limits per currency.

type TransferParams

type TransferParams struct {
	// From is the profile id the API key belongs to and where the funds are sourced
	From string `json:"from"`

	// To represents the target profile id of where funds will be transferred to
	To string `json:"to"`

	// Currency - i.e. BTC or USD
	Currency string `json:"currency"`

	// Amount is the amount of currency to be transferred
	Amount string `json:"amount"`
}

TransferParams represent all the required data you must provide for a call to transfer cryptocurrency between accounts.

type UKDepositInfo

type UKDepositInfo struct {
	SortCode      string `json:"sort_code"`
	AccountName   string `json:"account_name"`
	AccountNumber string `json:"account_number"`
	BankName      string `json:"bank_name"`
	Reference     string `json:"reference"`
}

UKDepositInfo describes all the metadata needed for a UK desposit.

type UserAccount

type UserAccount struct {
	ProductID      string `json:"product_id"`
	ExchangeVolume string `json:"exchange_volume"`
	Volume         string `json:"volume"`
	RecordedAt     string `json:"recorded_at"`
}

UserAccount is used for fetching trailing volumes for your user

type WireDepositInfo

type WireDepositInfo struct {
	AccountNumber  string      `json:"account_number"`
	RoutingNumber  string      `json:"routing_number"`
	BankName       string      `json:"bank_name"`
	BankAddress    string      `json:"bank_address"`
	BankCountry    BankCountry `json:"bank_country"`
	AccountName    string      `json:"account_name"`
	AccountAddress string      `json:"account_address"`
	Reference      string      `json:"reference"`
}

WireDepositInfo describes all the metadata needed for a wire deposit to a bank.

Jump to

Keyboard shortcuts

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