coinbasepro

package
v0.0.0-...-d86747b Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2021 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OrderStatusParamActive   = OrderStatusParam(OrderStatusActive)
	OrderStatusParamDone     = OrderStatusParam(OrderStatusDone)
	OrderStatusParamOpen     = OrderStatusParam(OrderStatusOpen)
	OrderStatusParamPending  = OrderStatusParam(OrderStatusPending)
	OrderStatusParamReceived = OrderStatusParam(OrderStatusReceived)
	OrderStatusParamSettled  = OrderStatusParam(OrderStatusSettled)

	// OrderStatusParamAll is only valid as a list filter param
	OrderStatusParamAll OrderStatusParam = "all"
)

Variables

This section is empty.

Functions

func Capture

func Capture(capture *error, deferred error)

Capture ensures errors from deferred funcs are captured when an error has not already been set.

func() (capture err) {
  w.Open()
  defer func() { Capture(&capture, w.Close()) }()
}

func DevelopmentMode

func DevelopmentMode(client *Client)

Types

type APIClient

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

func NewAPIClient

func NewAPIClient(baseURL *url.URL, feedURL *url.URL, auth *Auth) (*APIClient, error)

func (*APIClient) Close

func (a *APIClient) Close() error

func (*APIClient) Do

func (a *APIClient) Do(ctx context.Context, method string, relativePath string, content interface{}, result interface{}) (capture error)

func (*APIClient) Get

func (a *APIClient) Get(ctx context.Context, relativePath string, result interface{}) error

func (*APIClient) Post

func (a *APIClient) Post(ctx context.Context, relativePath string, content interface{}, result interface{}) error

type Account

type Account struct {
	// Funds available for withdrawal or trade
	Available decimal.Decimal `json:"available"`
	Balance   decimal.Decimal `json:"balance"`
	// Currency is the native currency of the account
	Currency CurrencyName    `json:"currency"`
	Hold     decimal.Decimal `json:"hold"`
	// ID of the account
	ID string `json:"id"`
	// ProfileID is the id of the profile to which the account belongs
	ProfileID      string `json:"profile_id"`
	TradingEnabled bool   `json:"trading_enabled"`
}

Account holds funds for trading on coinbasepro. Coinbasepro Accounts are separate from Coinbase accounts. You Deposit funds to begin trading.

type AccountType

type AccountType string
const (
	CoinbaseAccountTypeFiat   AccountType = "fiat"
	CoinbaseAccountTypeWallet AccountType = "wallet"
)

type AddressInfo

type AddressInfo struct {
	Address        string `json:"address"`
	DestinationTag string `json:"destination_tag"`
}

type AggregatedBookEntry

type AggregatedBookEntry struct {
	Price     decimal.Decimal `json:"price"`
	Size      decimal.Decimal `json:"size"`
	NumOrders int             `json:"num_orders"`
}

func (*AggregatedBookEntry) UnmarshalJSON

func (a *AggregatedBookEntry) UnmarshalJSON(b []byte) error

type AggregatedOrderBook

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

type AmountOfCurrency

type AmountOfCurrency struct {
	Amount   decimal.Decimal `json:"amount"`
	Currency CurrencyName    `json:"currency"`
}

type Auth

type Auth struct {
	Key        string
	Passphrase string
	Secret     string
}

Auth is required to sign requests to all private coinbasepro endpoints. Before being able to sign any requests, an API key must be created via the Coinbase Pro website. The API key will be scoped to a specific profile and assigned specific permissions at creation time.

  • View - Allows a key read permissions. This includes all GET endpoints.
  • Transfer - Allows a key to transfer currency on behalf of an account, including deposits and withdrawals. !! Enable Transfer with caution - API key transfers WILL BYPASS two-factor authentication. !!
  • Trade - Allows a key to enter orders, as well as retrieve trade data. This includes POST /orders and several GET endpoints.

Upon creating a key and providing a passphrase, the Secret will be generated.

!! All 3 pieces of information are required to authenticate requests to coinbasepro.

func NewAuth

func NewAuth(key string, passphrase string, secret string) *Auth

func (*Auth) Sign

func (a *Auth) Sign(message string) (string, error)

Sign creates a sha256 HMAC using the base64-decoded Secret key on the pre-hash string `timestamp + method + requestPath + body` (where + represents string concatenation) and then base64 encoding the output.

type BookEntry

type BookEntry struct {
	Price   decimal.Decimal `json:"price"`
	Size    decimal.Decimal `json:"size"`
	OrderID string          `json:"order_id"`
}

func (*BookEntry) UnmarshalJSON

func (b *BookEntry) UnmarshalJSON(raw []byte) error

type BookLevel

type BookLevel int

BookLevel represents the level of detail/aggregation in an OrderBook. BookLevelBest and BookLevelTop50 are aggregates. BookLevelFull requests the entire order book.

const (
	// BookLevelUndefined defaults to BookLevel_Best
	BookLevelUndefined BookLevel = 0
	// BookLevelBest requests only the best bid and ask and is aggregated.
	BookLevelBest BookLevel = 1
	// BookLevelTop50 requests the top 50 bids and asks and is aggregated.
	BookLevelTop50 BookLevel = 2
	// BookLevelFull is non-aggregated and returns the entire order book.
	BookLevelFull BookLevel = 3
)

func (BookLevel) Params

func (p BookLevel) Params() []string

type CancelOrderSpec

type CancelOrderSpec struct {
	// OrderID or ClientOrderID required.
	OrderID string `json:"order_id"`
	// ClientOrderID or OrderID is required.
	ClientOrderID string `json:"client_oid"`
	// ProductID is optional, but recommended for better performance
	ProductID ProductID `json:"product_id"`
}

func (CancelOrderSpec) Params

func (c CancelOrderSpec) Params() []string

func (CancelOrderSpec) Path

func (c CancelOrderSpec) Path() string

Path assumes Validate has been called and will panic if it cannot product a valid path.

func (CancelOrderSpec) Validate

func (c CancelOrderSpec) Validate() error

type Candle

type Candle struct {
	Close  decimal.Decimal `json:"close"`
	High   decimal.Decimal `json:"high"`
	Low    decimal.Decimal `json:"low"`
	Open   decimal.Decimal `json:"open"`
	Time   Time            `json:"time"`
	Volume decimal.Decimal `json:"volume"`
}

A Candle is a common representation of a historic rate.

func (*Candle) UnmarshalJSON

func (c *Candle) UnmarshalJSON(b []byte) error

type Channel

type Channel struct {
	Name       ChannelName `json:"name"`
	ProductIDs []ProductID `json:"product_ids"`
}

Channel is a feed of specific types messages for as specific set of products.

type ChannelName

type ChannelName string
const (
	// ChannelNameHeartbeat messages for specific products once a second subscribe to the heartbeat channel. Heartbeats
	// also include sequence numbers and last trade ids that can be used to verify no messages were missed.
	ChannelNameHeartbeat ChannelName = "heartbeat"
	// ChannelNameStatus will send all products and currencies on a preset interval.
	ChannelNameStatus ChannelName = "status"
	// ChannelNameTicker provides real-time price updates every time a match happens. It batches updates in case of
	// cascading matches, greatly reducing bandwidth requirements.
	ChannelNameTicker ChannelName = "ticker"
	// ChannelNameLevel2 provides a snapshot of the order book. It guarantees delivery of all updates, which has reduced
	// overhead compared to consuming the full channel.
	ChannelNameLevel2 ChannelName = "level2"
	// ChannelNameFull provides real-time updates on orders and trades. These updates can be applied on to a level 3
	// order book snapshot to maintain an accurate and up-to-date copy of the exchange order book.
	ChannelNameFull ChannelName = "full"
	// ChannelNameUser is a subset of the ChannelName_Full channel that only contains messages that reference the authenticated user.
	ChannelNameUser ChannelName = "user"
	// ChannelNameMatches only includes matches. Note that messages can be dropped from this channel.
	ChannelNameMatches ChannelName = "matches"
)

type Client

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

func NewClient

func NewClient(baseURL *url.URL, feedURL *url.URL, auth *Auth) (*Client, error)

NewClient creates a high-level Coinbase Pro API client.

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, spec CancelOrderSpec) (map[string]interface{}, error)

CancelOrder cancels a previously placed order. orderID is mandatory, productID is optional but will make the request more performant. If the Order had no matches during its lifetime, it may be subject to purge and as a result will no longer available via GetOrder. Requires "trade" permission.

func (*Client) Close

func (c *Client) Close() error

func (*Client) CreateCoinbaseAccountDeposit

func (c *Client) CreateCoinbaseAccountDeposit(ctx context.Context, coinbaseAccountDeposit CoinbaseAccountDeposit) (Deposit, error)

CreateCoinbaseAccountDeposit creates a Deposit of funds from a CoinbaseAccount. Funds can be moved between CoinbaseAccounts and Coinbase Pro trading Accounts within daily limits. Moving funds between Coinbase and Coinbase Pro is instant and free. Use ListCoinbaseAccounts to retrieve available Coinbase accounts.

func (*Client) CreateCoinbaseAccountWithdrawal

func (c *Client) CreateCoinbaseAccountWithdrawal(ctx context.Context, coinbaseAccountWithdrawal CoinbaseAccountWithdrawalSpec) (Withdrawal, error)

CreateCoinbaseAccountWithdrawal creates a Withdrawal of funds to a CoinbaseAccount. Funds can be moved between CoinbaseAccounts and Coinbase Pro trading Accounts within daily limits. Moving funds between Coinbase and Coinbase Pro is instant and free. Use ListCoinbaseAccounts to retrieve available Coinbase accounts.

func (*Client) CreateCryptoAddressWithdrawal

func (c *Client) CreateCryptoAddressWithdrawal(ctx context.Context, cryptoAddressWithdrawal CryptoAddressWithdrawalSpec) (Withdrawal, error)

CreateCryptoAddressWithdrawal creates a Withdrawal of funds to a crypto address.

func (*Client) CreateCryptoDepositAddress

func (c *Client) CreateCryptoDepositAddress(ctx context.Context, coinbaseAccountID string) (CryptoDepositAddress, error)

CreateCryptoDepositAddress generates an address for crypto deposits into a CoinbaseAccount.

func (*Client) CreateLimitOrder

func (c *Client) CreateLimitOrder(ctx context.Context, limitOrder LimitOrder) (Order, error)

CreateLimitOrder creates a LimitOrder to trade a Product with specified Price and Size limits.

func (*Client) CreateMarketOrder

func (c *Client) CreateMarketOrder(ctx context.Context, marketOrder MarketOrder) (Order, error)

CreateMarketOrder creates a MarketOrder with no pricing guarantees. A MarketOrder makes it easy to trade specific amounts of a Product without specifying prices.

func (*Client) CreatePaymentMethodDeposit

func (c *Client) CreatePaymentMethodDeposit(ctx context.Context, paymentMethodDeposit PaymentMethodDepositSpec) (Deposit, error)

CreatePaymentMethodDeposit creates a Deposit of funds from an external payment method. Use ListPaymentMethods to retrieve details of available PaymentMethods.

func (*Client) CreatePaymentMethodWithdrawal

func (c *Client) CreatePaymentMethodWithdrawal(ctx context.Context, paymentMethodWithdrawal PaymentMethodWithdrawalSpec) (Withdrawal, error)

CreatePaymentMethodWithdrawal creates a Withdrawal of funds to an external PaymentMethod. Use ListPaymentMethods to retrieve details of available PaymentMethods.

func (*Client) CreateProfileTransfer

func (c *Client) CreateProfileTransfer(ctx context.Context, transferSpec ProfileTransferSpec) (ProfileTransfer, error)

CreateProfileTransfer transfers funds between user Profiles.

func (*Client) CreateReport

func (c *Client) CreateReport(ctx context.Context, createReportSpec ReportSpec) (Report, error)

CreateReport creates request for batches of historic Profile information in various human and machine readable forms. Reports will be generated when resources are available. Report status can be queried using GetReport.

func (*Client) CreateStablecoinConversion

func (c *Client) CreateStablecoinConversion(ctx context.Context, stablecoinConversionSpec StablecoinConversionSpec) (StablecoinConversion, error)

CreateStablecoinConversion creates a conversion from a crypto Currency a stablecoin Currency.

func (*Client) GetAccount

func (c *Client) GetAccount(ctx context.Context, accountID string) (Account, error)

GetAccount retrieves the detailed representation of a trading Account. The requested Account must belong to the current Profile.

func (*Client) GetAggregatedOrderBook

func (c *Client) GetAggregatedOrderBook(ctx context.Context, productID ProductID, level BookLevel) (AggregatedOrderBook, error)

GetAggregatedOrderBook retrieves an aggregated, BookLevelBest (1) and BookLevelTop50 (2), representation of a Product OrderBook. Aggregated levels return only one Size for each active Price (as if there was only a single Order for that Size at the level).

func (*Client) GetClientOrder

func (c *Client) GetClientOrder(ctx context.Context, clientID string) (Order, error)

GetClientOrder retrieves the details of a single Order using a client-provided identifier. The requested Order must belong to the current Profile.

func (*Client) GetCurrency

func (c *Client) GetCurrency(ctx context.Context, currencyName CurrencyName) (Currency, error)

GetCurrency retrieves the details of a specific Currency.

func (*Client) GetDeposit

func (c *Client) GetDeposit(ctx context.Context, depositID string) (Deposit, error)

GetDeposit retrieves the details for a single Deposit. The Deposit must belong to the current Profile.

func (*Client) GetDeposits

func (c *Client) GetDeposits(ctx context.Context, filter DepositFilter, pagination PaginationParams) (Deposits, error)

GetDeposits retrieves a paginated list of Deposits, in descending order by CreatedAt time.

func (*Client) GetFees

func (c *Client) GetFees(ctx context.Context) (Fees, error)

GetFees returns current maker & taker fee rates, as well as the 30-day trailing volume. GetFees is plural, but returns a single object. Perhaps there is a better name.

func (*Client) GetFills

func (c *Client) GetFills(ctx context.Context, filter FillFilter, pagination PaginationParams) (Fills, error)

GetFills retrieves a paginated list of recent Fills for the current Profile.

func (*Client) GetHistoricRates

func (c *Client) GetHistoricRates(ctx context.Context, productID ProductID, filter HistoricRateFilter) (HistoricRates, error)

GetHistoricRates retrieves historic rates, as Candles, for a Product. Rates grouped buckets based on requested Granularity. If either one of the Start or End fields are not provided then both fields will be ignored. The Granularity is limited to a set of supported Timeslices, one of:

one minute, five minutes, fifteen minutes, one hour, six hours, or one day.

func (*Client) GetHolds

func (c *Client) GetHolds(ctx context.Context, accountID string, pagination PaginationParams) (Holds, error)

GetHolds retrieves the list of Holds for the Account. The requested Account must belong to the current Profile.

func (*Client) GetLedger

func (c *Client) GetLedger(ctx context.Context, accountID string, pagination PaginationParams) (Ledger, error)

GetLedger retrieves a paginated list of Account activity for the current Profile.

func (*Client) GetLimits

func (c *Client) GetLimits(ctx context.Context) (Limits, error)

GetLimits retrieves the payment method transfer limits and per currency buy/sell limits for the current Profile.

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, orderID string) (Order, error)

GetOrder retrieves the details of a single Order. The requested Order must belong to the current Profile.

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(ctx context.Context, productID ProductID) (OrderBook, error)

GetOrderBook retrieves the full, un-aggregated OrderBook for a Product.

func (*Client) GetOrders

func (c *Client) GetOrders(ctx context.Context, filter OrderFilter, pagination PaginationParams) (Orders, error)

GetOrders retrieves a paginated list of the current open orders for the current Profile. Only open or un-settled orders are returned by default. An OrderFilter can be used to further refine the request.

func (*Client) GetProduct

func (c *Client) GetProduct(ctx context.Context, productID ProductID) (Product, error)

GetProduct retrieves the details of a single Currency pair.

func (*Client) GetProductStats

func (c *Client) GetProductStats(ctx context.Context, productID ProductID) (ProductStats, error)

GetProductStats retrieves the 24hr stats for a Product. Volume is in base Currency units. Open, High, and Low are in quote Currency units.

func (*Client) GetProductTicker

func (c *Client) GetProductTicker(ctx context.Context, productID ProductID) (ProductTicker, error)

GetProductTicker retrieves snapshot information about the last trade (tick), best bid/ask and 24h volume of a Product.

func (*Client) GetProductTrades

func (c *Client) GetProductTrades(ctx context.Context, productID ProductID, pagination PaginationParams) (ProductTrades, error)

GetProductTrades retrieves a paginated list of the last trades of a Product.

func (*Client) GetProfile

func (c *Client) GetProfile(ctx context.Context, profileID string) (Profile, error)

GetProfile retrieves the details of a single Profile.

func (*Client) GetReport

func (c *Client) GetReport(ctx context.Context, reportID string) (Report, error)

GetReport retrieves the status of the processing of a Report request. When the ReportStatus is 'ready', the Report will be available for download at the FileURL.

func (*Client) GetServerTime

func (c *Client) GetServerTime(ctx context.Context) (ServerTime, error)

GetServerTime retrieves the Coinbase Pro API server time.

func (*Client) GetWithdrawal

func (c *Client) GetWithdrawal(ctx context.Context, withdrawalID string) (Withdrawal, error)

GetWithdrawal retrieves the details of a single Withdrawal. The Withdrawal must belong to the current Profile.

func (*Client) GetWithdrawalFeeEstimate

func (c *Client) GetWithdrawalFeeEstimate(ctx context.Context, cryptoAddress CryptoAddress) (WithdrawalFeeEstimate, error)

GetWithdrawalFeeEstimate retrieves the estimated network fees that would apply when sending to the given address.

func (*Client) GetWithdrawals

func (c *Client) GetWithdrawals(ctx context.Context, filter WithdrawalFilter, pagination PaginationParams) (Withdrawals, error)

GetWithdrawals retrieves a paginated list of Withdrawals for the current Profile, in descending order by CreatedAt time.

func (*Client) ListAccounts

func (c *Client) ListAccounts(ctx context.Context) ([]Account, error)

ListAccounts retrieves the list of trading accounts belonging to the Profile of the API key. The list is not paginated.

func (*Client) ListCoinbaseAccounts

func (c *Client) ListCoinbaseAccounts(ctx context.Context) ([]CoinbaseAccount, error)

ListCoinbaseAccounts retrieves the list of CoinbaseAccounts available for the current Profile. The list is not paginated.

func (*Client) ListCurrencies

func (c *Client) ListCurrencies(ctx context.Context) ([]Currency, error)

ListCurrencies retrieves the list of known Currencies. Not all Currencies may be available for trading.

func (*Client) ListPaymentMethods

func (c *Client) ListPaymentMethods(ctx context.Context) ([]PaymentMethod, error)

ListPaymentMethods retrieves the list of PaymentMethods available for the current Profile. The list is not paginated.

func (*Client) ListProducts

func (c *Client) ListProducts(ctx context.Context) ([]Product, error)

ListProducts retrieves the list Currency pairs available for trading. The list is not paginated.

func (*Client) ListProfiles

func (c *Client) ListProfiles(ctx context.Context, filter ProfileFilter) ([]Profile, error)

ListProfiles retrieves a list of Profiles (portfolio equivalents). A given user can have a maximum of 10 profiles. The list is not paginated.

func (*Client) Watch

func (c *Client) Watch(ctx context.Context, subscriptionRequest SubscriptionRequest, feed Feed) (capture error)

Watch provides a feed of real-time market data updates for orders and trades.

type CoinbaseAccount

type CoinbaseAccount struct {
	Active                 bool                   `json:"active"`
	Balance                decimal.Decimal        `json:"balance"`
	Currency               CurrencyName           `json:"currency"`
	ID                     string                 `json:"id"`
	Name                   string                 `json:"name"`
	Primary                bool                   `json:"primary"`
	Type                   AccountType            `json:"type"`
	WireDepositInformation WireDepositInformation `json:"wire_deposit_information"`
	SEPADepositInformation SEPADepositInformation `json:"sepa_deposit_information"`
}

type CoinbaseAccountDeposit

type CoinbaseAccountDeposit struct {
	Amount            decimal.Decimal `json:"amount"`
	Currency          CurrencyName    `json:"currency"`
	CoinbaseAccountID string          `json:"coinbase_account_id"`
}

CoinbaseAccountDeposit describes the payout from a CoinbaseAccount

func (*CoinbaseAccountDeposit) UnmarshalJSON

func (c *CoinbaseAccountDeposit) UnmarshalJSON(b []byte) error

type CoinbaseAccountWithdrawalSpec

type CoinbaseAccountWithdrawalSpec struct {
	Amount            decimal.Decimal `json:"amount"`
	Currency          CurrencyName    `json:"currency"`
	CoinbaseAccountID string          `json:"coinbase_account_id"`
}

CoinbaseAccountWithdrawalSpec creates payout to a CoinbaseAccount

func (*CoinbaseAccountWithdrawalSpec) UnmarshalJSON

func (c *CoinbaseAccountWithdrawalSpec) UnmarshalJSON(b []byte) error

type Country

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

type CryptoAddress

type CryptoAddress struct {
	Currency      CurrencyName `json:"currency"`
	CryptoAddress string       `json:"crypto_address"`
}

func (CryptoAddress) Params

func (c CryptoAddress) Params() []string

func (*CryptoAddress) UnmarshalJSON

func (c *CryptoAddress) UnmarshalJSON(b []byte) error

type CryptoAddressWithdrawalSpec

type CryptoAddressWithdrawalSpec struct {
	// AddNetworkFeeToTotal indicates that the network fee should be added to the amount
	// By default, network fees are deducted from the amount
	AddNetworkFeeToTotal bool `json:"add_network_fee_to_total"`
	// Amount to withdraw
	Amount decimal.Decimal `json:"amount"`
	// Crypto address of the recipient
	CryptoAddress string `json:"crypto_address"`
	// Currency to withdraw
	Currency CurrencyName `json:"currency"`
	// DestinationTag for currencies that support destination tagging
	DestinationTag string `json:"destination_tag"`
	// NoDestinationTag opts out of using a destination tag: required when not providing a destination tag
	NoDestinationTag bool `json:"no_destination_tag"`
}

func (*CryptoAddressWithdrawalSpec) UnmarshalJSON

func (c *CryptoAddressWithdrawalSpec) UnmarshalJSON(b []byte) error

type CryptoDepositAddress

type CryptoDepositAddress struct {
	Address                string      `json:"address"`
	AddressInfo            AddressInfo `json:"address_info"`
	CreatedAt              Time        `json:"created_at"`
	DepositURI             string      `json:"deposit_uri"` // ?url.URL
	DestinationTag         string      `json:"destination_tag"`
	ExchangeDepositAddress bool        `json:"exchange_deposit_address"`
	ID                     string      `json:"id"`
	Network                string      `json:"network"`
	Resource               string      `json:"resource"`
	UpdatedAt              Time        `json:"updated_at"`
}

type CryptoWithdrawal

type CryptoWithdrawal struct {
	Amount   decimal.Decimal `json:"amount"`
	Currency CurrencyName    `json:"currency"`
	Fee      decimal.Decimal `json:"fee"`
	ID       string          `json:"id"`
	Subtotal decimal.Decimal `json:"subtotal"`
}

type Currency

type Currency struct {
	ConvertibleTo []CurrencyName  `json:"convertible_to"`
	Details       CurrencyDetails `json:"details"`
	ID            string          `json:"id"`
	MaxPrecision  decimal.Decimal `json:"max_precision"`
	Message       string          `json:"message"`
	MinSize       decimal.Decimal `json:"min_size"`
	Name          string          `json:"name"`
	Status        string          `json:"status"`
}

type CurrencyDetails

type CurrencyDetails map[string]interface{}

type CurrencyLimit

type CurrencyLimit map[CurrencyName]Limit

type CurrencyName

type CurrencyName string

type Deposit

type Deposit struct {
	// AccountID identifies the Account to which the Deposit applies
	AccountID string `json:"account_id"`
	// Amount is the amount of the Deposit
	Amount decimal.Decimal `json:"amount"`
	// CanceledAt is the time of cancellation, if the Deposit was canceled
	CanceledAt *Time `json:"canceled_at"`
	// CompletedAt is the time of completion, if the Deposit was completed
	CompletedAt *Time `json:"completed_at"`
	// CreatedAt is the time of creation
	CreatedAt Time `json:"created_at"`
	// CreatedAt is the time the Deposit was created
	Currency CurrencyName `json:"currency"`
	// Details provides more fine-grained information describing the Deposit
	Details DepositDetails `json:"details"`
	// ProcessedAt is the time the Deposit was processed
	ProcessedAt *Time `json:"processed_at"`
	// ID uniquely identifies the Deposit
	ID string `json:"id"`
	// Type identifies the type of the Deposit (`deposit` or `internal_deposit`)
	Type DepositType `json:"type"`
	// UserID that initiated the Deposit
	UserID    string `json:"user_id"`
	UserNonce string `json:"user_nonce"`
}

Deposit represents the movement of Currency into accounts from both external and internal sources. Deposits are implemented as Transfers, but I assume this was confusing/naive, as the documentation rebrands Transfers as Deposits. I have followed the hint and done the same.

type DepositDetails

type DepositDetails map[string]interface{}

DepositDetails is not well documented; until proven or requested otherwise, I will simply treat the details as free form annotations or labels.

type DepositFilter

type DepositFilter struct {
	// ProfileID limits the list of Deposits to the ProfileID. By default, Deposits retrieves Deposits for the default profile.
	ProfileID string `json:"profile_id"`
	// Type identifies the type of the Deposit (`deposit` or `internal_deposit`)
	Type DepositType `json:"type"`
}

DepositFilter filters the list of deposits to be retrieved.

func (*DepositFilter) Params

func (d *DepositFilter) Params() []string

Params transforms the filter into query params.

type DepositType

type DepositType string
const (
	// DepositTypeDeposit indicates a deposit to a portfolio from an external source
	DepositTypeDeposit DepositType = "deposit"
	// DepositTypeInternal indicates a transfer between portfolios
	DepositTypeInternal DepositType = "internal_deposit"
)

func (DepositType) Valid

func (d DepositType) Valid() error

type Deposits

type Deposits struct {
	Deposits []*Deposit  `json:"deposits"`
	Page     *Pagination `json:"page,omitempty"`
}

Deposits is a paged collection of Deposits

func (*Deposits) UnmarshalJSON

func (d *Deposits) UnmarshalJSON(b []byte) error

type DevelopmentClient

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

func NewDevelopmentClient

func NewDevelopmentClient(client *APIClient, fs afero.Fs) (d *DevelopmentClient, capture error)

func (*DevelopmentClient) Close

func (d *DevelopmentClient) Close() (capture error)

func (*DevelopmentClient) Do

func (d *DevelopmentClient) Do(ctx context.Context, method string, relativePath string, content interface{}, result interface{}) (capture error)

func (*DevelopmentClient) Get

func (d *DevelopmentClient) Get(ctx context.Context, relativePath string, result interface{}) error

func (*DevelopmentClient) Post

func (d *DevelopmentClient) Post(ctx context.Context, relativePath string, content interface{}, result interface{}) error

type Error

type Error struct {
	StatusCode int    `json:"code"`
	Message    string `json:"message"`
}

func (Error) Error

func (e Error) Error() string

type Feed

type Feed struct {
	Subscriptions chan SubscriptionRequest
	Messages      chan interface{}
}

func NewFeed

func NewFeed() Feed

type Fees

type Fees struct {
	MakerFeeRate decimal.Decimal `json:"maker_fee_rate"`
	TakerFeeRate decimal.Decimal `json:"taker_fee_rate"`
	USDVolume    decimal.Decimal `json:"usd_volume"`
}

Fees describes the current maker & taker fee rates, as well as the 30-day trailing volume. Quoted rates are subject to change. Note: the docs (https://docs.pro.coinbase.com/#fees) are wrong; the response is an object, not an array

type Fill

type Fill struct {
	// CreatedAt is the fill creation time
	CreatedAt Time `json:"created_at"`
	// Fee indicates the fees charged for this individual Fill.
	Fee decimal.Decimal `json:"fee"`
	// Liquidity indicates if the fill was the result of a liquidity maker or liquidity taker
	Liquidity LiquidityType `json:"liquidity"`
	// OrderID identifies the order associated with the Fill
	OrderID string `json:"order_id"`
	// Price per unit of Product
	Price decimal.Decimal `json:"price"`
	// ProductID identifies the Product associated with the Order
	ProductID ProductID `json:"product_id"`
	// Settled indicates if the Fill has been settled and the counterparties credited
	Settled bool `json:"settled"`
	// Side of Order, `buy` or `sell`
	Side Side `json:"side"`
	// Size indicates the amount of Product filled
	Size decimal.Decimal `json:"size"`
	// TradeID TODO: ??
	TradeID int64 `json:"trade_id"`
}

Fill Settlement and Fees 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.

type FillFilter

type FillFilter struct {
	// OrderID limits the list of Fills to those with the specified OrderID
	OrderID string `json:"order-id"`
	// ProductID limits the list of Fills to those with the specified ProductID
	ProductID ProductID `json:"product-id"`
}

func (FillFilter) Params

func (f FillFilter) Params() []string

type Fills

type Fills struct {
	Fills []*Fill     `json:"fills"`
	Page  *Pagination `json:"page,omitempty"`
}

Fills is a paged collection of Fills

func (*Fills) UnmarshalJSON

func (f *Fills) UnmarshalJSON(b []byte) error

type HistoricRateFilter

type HistoricRateFilter struct {
	Granularity Timeslice `json:"granularity"`
	End         Time      `json:"end"`
	Start       Time      `json:"start"`
}

HistoricRateFilter holds filters historic rates for a product by date and sets the granularity of the response. 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, the request will be rejected. These values correspond to time slices representing: one minute, five minutes, fifteen minutes, one hour, six hours, and one day, respectively. If data points are readily available, the response may contain as many as 300 candles and some of candles may precede the start value. The maximum number of data points for a single request is 300 candles. If the start/end time and granularity results in more than 300 data points, the request will be rejected. To retrieve finer granularity data over a larger time range, multiple requests with new start/end ranges must be used.

func (*HistoricRateFilter) Params

func (h *HistoricRateFilter) Params() []string

type HistoricRates

type HistoricRates struct {
	Candles []*Candle
}

func (*HistoricRates) UnmarshalJSON

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

type Hold

type Hold struct {
	// Account identifies the Account to which the Hold applies
	AccountID string `json:"account_id"`
	// Amount of hold
	Amount decimal.Decimal `json:"amount"`
	// Time hold was created
	CreatedAt Time `json:"created_at"`
	// Ref contains the id of the order or transfer which created the hold.
	Ref string `json:"ref"`
	// Type of indicates whether the Hold is the result of open orders or withdrawals.
	Type HoldType `json:"type"`
	// Time order was filled
	UpdatedAt Time `json:"updated_at"`
}

A Hold will make the Amount of funds unavailable for trade or withdrawal.

type HoldType

type HoldType string

HoldType indicates why the hold exists.

const (
	// HoldTypeOpenOrders type holds are related to open orders.
	HoldTypeOpenOrders HoldType = "order"
	// HoldTypeWithdrawal type holds are related to a withdrawal.
	HoldTypeWithdrawal HoldType = "transfer"
)

type Holds

type Holds struct {
	Holds []*Hold     `json:"holds"`
	Page  *Pagination `json:"page,omitempty"`
}

Holds are placed on an account for any active orders or pending withdraw requests. For `limit buy` orders, Price x Size x (1 + fee-percent) USD will be held. For sell orders, the number of base currency to be sold is held. Actual Fees are assessed at time of trade. If a partially filled or unfilled Order is canceled, any remaining funds will be released from hold. For a MarketOrder `buy` with Order.Funds, the Order.Funds amount will be put on hold. If only Order.Size is specified, the total Account.Balance (in the quote account) will be put on hold for the duration of the MarketOrder (usually a trivially short time). For a 'sell' Order, the Order.Size in base currency will be put on hold. If Order.Size is not specified (and only Order.Funds is specified), the entire base currency balance will be on hold for the duration of the MarketOrder.

func (*Holds) UnmarshalJSON

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

UnmarshalJSON allows the raw slice of entries to be mapped to a named field on the struct. Pagination details are added post-unmarshal.

type Ledger

type Ledger struct {
	Entries []*LedgerEntry `json:"entries"`
	Page    *Pagination    `json:"page"`
}

Ledger holds the detailed activity of the profile associated with the current API key. Ledger is paginated and sorted newest first.

func (*Ledger) UnmarshalJSON

func (l *Ledger) UnmarshalJSON(b []byte) error

UnmarshalJSON allows the raw slice of entries to be mapped to a named field on the struct. Pagination details are added post-unmarshal.

type LedgerDetails

type LedgerDetails struct {
	OrderID   string `json:"order_id"`
	ProductID string `json:"product_id"`
	TradeID   string `json:"trade_id"`
}

LedgerDetails contains additional details for LedgerEntryTypeFee and LedgerEntryTypeMatch trades.

type LedgerEntry

type LedgerEntry struct {
	// Amount of the transaction
	Amount decimal.Decimal `json:"amount"`
	// Balance after transaction applied
	Balance decimal.Decimal `json:"balance"`
	// CreatedAt is the timestamp of the transaction time
	CreatedAt Time `json:"created_at"`
	// Details will contain additional information if an entry is the result of a trade ('match', 'fee')
	Details LedgerDetails `json:"details"`
	// ID of the transaction
	ID string `json:"id"`
	// Type of transaction ('conversion', 'fee', 'match', 'rebate')
	Type LedgerEntryType `json:"type"`
}

LedgerEntry represents an instance of account activity. A LedgerEntry will either increase or decrease the Account balance.

type LedgerEntryType

type LedgerEntryType string

LedgerEntryType describes the reason for the account balance change.

const (
	// LedgerEntryTypeConversion funds converted between fiat currency and a stablecoin
	LedgerEntryTypeConversion LedgerEntryType = "conversion"
	// LedgerEntryTypeFee funds moved to/from Coinbase to Coinbase Pro
	LedgerEntryTypeFee LedgerEntryType = "fee"
	// LedgerEntryTypeMatch funds moved as a result of a trade
	LedgerEntryTypeMatch LedgerEntryType = "match"
	// LedgerEntryTypeRebate fee rebate as per coinbasepro fee schedule (see https://pro.coinbase.com/fees)
	LedgerEntryTypeRebate LedgerEntryType = "rebate"
)

type Limit

type Limit struct {
	Max          decimal.Decimal `json:"max"`
	Remaining    decimal.Decimal `json:"remaining"`
	PeriodInDays int             `json:"period_in_days"`
}

TODO: haven't ever seen PeriodInDays

type LimitOrder

type LimitOrder struct {
	// Common Order fields
	// ClientOrderID is a client provided order UUID (optional)
	// The received ClientOrderID field value will be broadcast in the public feed for received messages.
	// The ClientOrderID can be used to identify orders in the public feed.
	// If you are consuming the public feed and see a received message with your ClientOrderID,
	// your application *must* record the server-assigned order_idl; the ClientOrderID will not be present on subsequent order status updates.
	// The ClientOrderID will *not* be used after initial broadcast message is sent.
	ClientOrderID string `json:"client_oid"`
	// Must be a valid product ID
	ProductID ProductID `json:"product_id"`
	// SelfTradePrevention determines the method used to prevent orders from the same user from matching with each other.
	// The default SelfTrade prevention method is SelfTradeDecrementAndCancel.
	SelfTradePrevention SelfTrade `json:"stp"`
	// Side type of order, `buy` or `sell`
	Side Side `json:"side"`

	// Stop type of order `entry` or `loss` - requires `stop_price`
	Stop Stop `json:"stop"`
	// StopPrice only if `stop` is defined, sets trigger price for stop order
	StopPrice *decimal.Decimal `json:"stop_price"`

	// LimitOrder must always have an OrderType of `limit`
	Type OrderType `json:"type"`

	// Limit-specific fields
	// TODO: I don't see an example of this, need to make one... WTF does it look like?
	// CancelAfter min, hour, day. (optional) except for LimitOrderTimeInForce_GoodTillTime (required)
	CancelAfter string `json:"cancel_after"`
	// TODO: what does this do? Is it a "dry-run", or some other limitation. Docs suck.
	// PostOnly indicates whether only maker orders can be placed. Invalid when TimeInForce is IOC or FOK.
	// No orders will be matched when PostOnly mode is active.
	// PostOnly indicates that the order should only make liquidity. If any part of the order results in taking liquidity,
	// the order will be rejected and no part of it will execute.
	PostOnly bool `json:"post_only"`
	// Price per unit of product
	// 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.
	// A Price of less than 1 penny will not be accepted, and no fractional penny prices will be accepted.
	Price decimal.Decimal `json:"price"`
	// Size indicates the amount of Product to buy or sell.
	// Size must be greater than the Product BaseMinSize and no larger than the BaseMaxSize.
	// Size can be in incremented in units of BaseIncrement.
	Size decimal.Decimal `json:"size"`
	// TimeInForce describes the time the order is effective: GTC, GTT, IOC, or FOK (default is GTC)
	TimeInForce TimeInForce `json:"time_in_force"`
}

LimitOrder is both the default and basic order type. A LimitOrder requires specifying a Price} and Size. The Size is the number of base currency to buy or sell, and the Price is the price per base currency. The LimitOrder will be filled at the price specified or better. A `sell` order can be filled at the specified price per base currency or a higher price per base currency and a `buy` order can be filled at the specified price or a lower price depending on market conditions. If market conditions cannot fill the limit order immediately, then the limit order will become part of the open order book until filled by another incoming order or canceled by the user.

func (*LimitOrder) UnmarshalJSON

func (l *LimitOrder) UnmarshalJSON(b []byte) error

func (*LimitOrder) Validate

func (l *LimitOrder) Validate() error

Validate likely needs more validations

type LimitOrderSpecific

type LimitOrderSpecific struct {
	// TODO: I don't see an example of this, need to make one... WTF does it look like?
	// CancelAfter min, hour, day. (optional) except for TimeInForceGoodTillTime (required)
	CancelAfter string `json:"cancel_after"`
	// TODO: what does this do? Is it a "dry-run", or some other limitation. Docs suck.
	// PostOnly indicates whether only maker orders can be placed. Invalid when time_in_force is IOC or FOK.
	// No orders will be matched when post_only mode is active.
	// PostOnly indicates that the order should only make liquidity. If any part of the order results in taking liquidity,
	// the order will be rejected and no part of it will execute.
	PostOnly bool `json:"post_only"`
	// Price per unit of product
	// 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.
	// A Price of less than 1 penny will not be accepted, and no fractional penny prices will be accepted.
	Price decimal.Decimal `json:"price"`
	// Size indicates the amount of Product to buy or sell.
	// Size must be greater than the Product BaseMinSize and no larger than the BaseMaxSize.
	// Size can be in incremented in units of BaseIncrement.
	Size decimal.Decimal `json:"size"`
	// TimeInForce describes the time the order is effective: GTC, GTT, IOC, or FOK (default is GTC)
	TimeInForce TimeInForce `json:"time_in_force"`
}

LimitOrderSpecific are fields that only apply to an OrderTypeLimit Order, which is both the default and the basic order type. A LimitOrder requires specifying a Price and Size. The Size is the number of base currency to buy or sell, and the Price is the price per base currency. The LimitOrder will be filled at the price specified or better. A SideSell order can be filled at the specified price per base currency or a higher price per base currency and a SideBuy order can be filled at the specified price or a lower price depending on market conditions. If market conditions cannot fill the limit order immediately, then the limit order will become part of the open order book until filled by another incoming order or canceled by the user.

type Limits

type Limits struct {
	LimitCurrency  CurrencyName             `json:"limit_currency"`
	TransferLimits map[string]CurrencyLimit `json:"transfer_limits"`
}

Limits provide payment method transfer limits, as well as buy/sell limits per currency.

type LiquidityType

type LiquidityType string
const (
	// LiquidityTypeMaker indicates the Fill was the result of a liquidity provider
	LiquidityTypeMaker LiquidityType = "M"
	// LiquidityTypeTaker indicates the Fill was the result of a liquidity taker
	LiquidityTypeTaker LiquidityType = "T"
)

type MarketOrder

type MarketOrder struct {
	// Common Order fields
	// ClientOrderID is a client provided order UUID (optional)
	// The received ClientOrderID field value will be broadcast in the public feed for received messages.
	// The ClientOrderID can be used to identify orders in the public feed.
	// If you are consuming the public feed and see a received message with your ClientOrderID,
	// your application *must* record the server-assigned order id; the ClientOrderID will not be present on subsequent order status updates.
	// The ClientOrderID will *not* be used after initial broadcast message is sent.
	ClientOrderID string `json:"client_oid"`
	// ProductID must be a valid product ID
	ProductID ProductID `json:"product_id"`
	// SelfTradePrevention determines the method used to prevent orders from the same user from matching with each other.
	// The default SelfTrade prevention method is SelfTradeDecrementAndCancel.
	SelfTradePrevention SelfTrade `json:"stp"`
	// Side type of order, `buy` or `sell`
	Side Side `json:"side"`
	// Stop type of order, `entry` or `loss` - requires `stop_price`
	Stop Stop `json:"stop"`
	// StopPrice only if `stop` is defined, sets trigger price for stop order
	StopPrice *decimal.Decimal `json:"stop_price"`
	// Type of order, `limit` or `market` (`default` is limit)
	// MarketOrder must always have Type `market`
	Type OrderType `json:"type"`

	// MarketOrder-specific fields
	// Funds desired amount of quote currency to use (optional).
	// Funds indicates how much of the product quote currency to buy or sell. For example, a market buy for BTC-USD
	// With Funds of 150.00, the order will use 150 USD to buy BTC (including any fees).
	// Without Funds, the size *must* be specified and Coinbase Pro will use available funds in your account to execute the order.
	// 	A MarkerOrder with Type `sell` can also specify Funds, if provided Funds will limit the `sell` to the amount specified.
	Funds *decimal.Decimal `json:"funds"`
	// Size is number of units of product to buy or sell (optional)
	Size *decimal.Decimal `json:"size"`
}

MarketOrder differs from a LimitOrder in that MarketOrder provided no pricing guarantees. MarketOrder do provide a way buy or sell specific amounts of base currency or fiat without having to specify the Price. A MarketOrder will execute immediately and no part of the order will go on the open order book. Market orders are always considered takers and incur taker fees. When placing a market order you can specify Funds and/or Size. Funds will limit how much of your quote currency account balance is used and Size will limit the amount of base currency transacted. MarketOrder requires one of Funds or Size.

func (*MarketOrder) UnmarshalJSON

func (m *MarketOrder) UnmarshalJSON(b []byte) error

func (*MarketOrder) Validate

func (m *MarketOrder) Validate() error

type MarketOrderSpecific

type MarketOrderSpecific struct {

	// 	A MarkerOrder with Type `sell` can also specify Funds, if provided Funds will limit the `sell` to the amount specified.
	Funds decimal.Decimal `json:"funds"`
	// Size is number of units of product to buy or sell (optional)
	Size decimal.Decimal `json:"size"`
}

MarketOrderSpecific fields apply only to a MarketOrder. A MarketOrder differs from a LimitOrder in that they provide no pricing guarantees. They however do provide a way to buy or sell specific amounts of base currency or fiat without having to specify the price. Market orders execute immediately and no part of the market order will go on the open order book. Market orders are always considered takers and incur taker fees. When placing a market order you can specify funds and/or size. Funds will limit how much of your quote currency account balance is used and Size will limit the amount of base currency transacted. A MarketOrder requires one of Funds or Size.

type MessageType

type MessageType string
const (
	MessageTypeError MessageType = "error"
	MessageTypeOpen  MessageType = "open"
	// MessageTypeSubscribe messages are sent to the server and indicate which channels and products to receive.
	MessageTypeSubscribe   MessageType = "subscribe"
	MessageTypeUnsubscribe MessageType = "unsubscribe"
)

type Order

type Order struct {
	// CreatedAt is the order creation time
	CreatedAt Time `json:"created_at"`
	// CreatedAt is the order completion time
	DoneAt Time `json:"done_at"`
	// DoneReason describes how the order completed
	DoneReason string `json:"done_reason"`
	// ExecutedValue is the value of the order at completion time
	ExecutedValue *decimal.Decimal `json:"executed_value"`
	// FillFees are the total fees for the order
	FillFees *decimal.Decimal `json:"fill_fees"`
	// FilledSize is the amount of Product the filled the order
	FilledSize *decimal.Decimal `json:"filled_size"`
	// Funds is the amount of Funds the the Order actually provides
	Funds *decimal.Decimal `json:"funds"`
	// ID is the server-generated ID of the Order.
	ID string `json:"id"`
	// PostOnly indicates whether only maker orders can be placed. No orders will be matched when post_only mode is active.
	// When PostOnly is true, if any part of the order results in taking liquidity the order will be rejected and no part of it will execute.
	PostOnly bool `json:"post_only"`
	// ProductID identifies the Product associated with the Order
	ProductID ProductID `json:"product_id"`
	// Settled indicates settlement status
	Settled bool `json:"settled"`
	// Side of order, `buy` or `sell`
	Side Side `json:"side"`
	// Size indicates the amount of Product to buy or sell.
	Size decimal.Decimal `json:"size"`
	// SpecifiedFunds TODO: ?
	SpecifiedFunds *decimal.Decimal `json:"specified_funds"`
	// Status indicates the current Order state in the Order Lifecycle
	Status OrderStatus `json:"status"`
	// SelfTradePrevention determines the method(optional).
	// Self-trading is not allowed on Coinbase Pro. Two orders from the same user will not be allowed to match with
	// one another. SelfTradeDecrementAndCancel is the default.
	SelfTradePrevention SelfTrade `json:"stp"`
	// Type of order, `limit` or `market` (`default` is limit)
	Type OrderType `json:"type"`
}

Order

Price Improvement Orders are matched against existing order book orders at the price of the order on the book, not at the price of the taker order.

EXAMPLE User A places a Buy order for 1 BTC at 100 USD. User B then wishes to sell 1 BTC at 80 USD. Because User A's order was first to the trading engine, they will have price priority and the trade will occur at 100 USD.

Order Lifecycle Valid orders sent to the matching engine are confirmed immediately and are in the `received` state. If an order executes against another order immediately, the order is considered `done`. An order can execute in part or whole. Any part of the order not filled immediately will be considered `open`. Orders will stay in the `open` state until canceled or subsequently filled by new orders. Orders that are no longer eligible for matching (filled or canceled) are in the done state.

Order Status and Settlement 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.

Polling 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.

type OrderBook

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

type OrderFilter

type OrderFilter struct {
	// ProductID limits the list of Orders to those with the specified ProductID
	ProductID ProductID `json:"product-id"`
	// Status limits list of Orders to the provided OrderStatuses. The default, OrderStatusParamAll, returns orders of all statuses
	Status []OrderStatusParam `json:"status"`
}

func (OrderFilter) Params

func (o OrderFilter) Params() []string

func (OrderFilter) Validate

func (o OrderFilter) Validate() error

type OrderStatus

type OrderStatus string

OrderStatus indicates the current Order state in the Order Lifecycle

const (
	OrderStatusActive   OrderStatus = "active"
	OrderStatusDone     OrderStatus = "done"
	OrderStatusOpen     OrderStatus = "open"
	OrderStatusPending  OrderStatus = "pending"
	OrderStatusReceived OrderStatus = "received"
	OrderStatusSettled  OrderStatus = "settled"
)

type OrderStatusParam

type OrderStatusParam OrderStatus

OrderStatusParam is a superset of OrderStatus which includes the filter-only OrderStatusParamAll

func (OrderStatusParam) Validate

func (o OrderStatusParam) Validate() error

type OrderType

type OrderType string

OrderType influences which other order parameters are required and how the order will be executed by the matching engine. If OrderType is not specified, the order will default to a LimitOrder.

const (
	OrderTypeMarket OrderType = "market"
	OrderTypeLimit  OrderType = "limit"
)

type Orders

type Orders struct {
	Orders []*Order    `json:"orders"`
	Page   *Pagination `json:"page,omitempty"`
}

Orders is a paged collection of Orders

func (*Orders) UnmarshalJSON

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

type Pagination

type Pagination struct {
	After  string `json:"after,omitempty"`
	Before string `json:"before,omitempty"`
}

Pagination uses the response from the coinbase pro REST API to populate a pair of page tokens which can be used to navigate forwards/backwards through a paginated response. The before/after nomenclature is a direct lift from the coinbase pro REST API which, as their own docs state, "is unintuitive at first," because most paginated requests return the latest information (newest) as the first page. Because the pages are sorted by newest (in chronological time) first, to get older information, use the `before` token. Just need to keep in mind: the `before` and `after` refer to sort order and not chronological time. It makes sense, but just barely.

func (*Pagination) NotEmpty

func (p *Pagination) NotEmpty() bool

NotEmpty provides a convenience for determining when a response is Paginated. Pagination will be populated for Paginated responses.

type PaginationParams

type PaginationParams struct {
	After  string `json:"after"`
	Before string `json:"before"`
	Limit  int    `json:"limit"`
}

PaginationParams allow for requests to limit the number of responses as well as request the next page of responses either Before or After the current Page in sort order. The sort order is endpoint dependent, though will tend to be chronological, with newest first. A Limit of 0 will be defaulted to 100, and 100 is also the maximum allowed value.

func (PaginationParams) Params

func (p PaginationParams) Params() []string

func (PaginationParams) Validate

func (p PaginationParams) Validate() error

type PaymentMethod

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

PaymentMethod describes a source of currency

type PaymentMethodDeposit

type PaymentMethodDeposit struct {
	Amount   decimal.Decimal `json:"amount"`
	Currency CurrencyName    `json:"currency"`
	ID       string          `json:"id"`
}

PaymentMethodDeposit describes the payout from a PaymentMethodDepositSpec

type PaymentMethodDepositSpec

type PaymentMethodDepositSpec struct {
	Amount          decimal.Decimal `json:"amount"`
	Currency        CurrencyName    `json:"currency"`
	PaymentMethodID string          `json:"payment_method_id"`
}

PaymentMethodDepositSpec deposits funds from a PaymentMethod

func (*PaymentMethodDepositSpec) UnmarshalJSON

func (p *PaymentMethodDepositSpec) UnmarshalJSON(b []byte) error

type PaymentMethodLimit

type PaymentMethodLimit struct {
	PeriodInDays int              `json:"period_in_days"`
	Total        AmountOfCurrency `json:"total"`
	Remaining    AmountOfCurrency `json:"remaining"`
}

type PaymentMethodLimits

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

type PaymentMethodWithdrawalSpec

type PaymentMethodWithdrawalSpec struct {
	Amount          decimal.Decimal `json:"amount"`
	Currency        CurrencyName    `json:"currency"`
	PaymentMethodID string          `json:"payment_method_id"`
}

PaymentMethodWithdrawalSpec withdraw funds using a PaymentMethod

func (*PaymentMethodWithdrawalSpec) UnmarshalJSON

func (p *PaymentMethodWithdrawalSpec) UnmarshalJSON(b []byte) error

type Product

type Product struct {
	// BaseCurrency is the base in the pair of currencies that comprise the Product
	BaseCurrency CurrencyName `json:"base_currency"`
	// BaseIncrement specifies the minimum increment for the BaseCurrency
	BaseIncrement decimal.Decimal `json:"base_increment"`
	// BaseMaxSize defines the maximum order size
	BaseMaxSize decimal.Decimal `json:"base_max_size"`
	// BaseMinSize defines the minimum order size
	BaseMinSize decimal.Decimal `json:"base_min_size"`
	DisplayName string          `json:"display_name"`
	ID          string          `json:"id"`
	// MaxMarketFunds defines the maximum funds allowed
	MaxMarketFunds decimal.Decimal `json:"max_market_funds"`
	// MinMarketFunds defines the minimum funds allowed
	MinMarketFunds decimal.Decimal `json:"min_market_funds"`
	QuoteCurrency  CurrencyName    `json:"quote_currency"`
	QuoteIncrement decimal.Decimal `json:"quote_increment"`
	Status         ProductStatus   `json:"status"`
	// StatusMessage provides any extra information regarding the status, if available
	StatusMessage string `json:"status_message"`
	// CancelOnly indicates whether this product only accepts cancel requests for orders.
	CancelOnly bool `json:"cancel_only"`
	// LimitOnly indicates whether this product only accepts limit orders.
	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 cancellations are restricted.
	TradingDisabled bool `json:"trading_disabled"`
}

Product 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. !! When limit_only is true, matching can occur if a limit order crosses the book. !! Product ID will not change once assigned to a Product but all other fields are subject to change.

type ProductID

type ProductID string

ProductID values could perhaps be dynamically validated from '/products' endpoint

type ProductStats

type ProductStats struct {
	High        decimal.Decimal `json:"high"`
	Last        decimal.Decimal `json:"last"`
	Low         decimal.Decimal `json:"low"`
	Open        decimal.Decimal `json:"open"`
	Volume      decimal.Decimal `json:"volume"`
	Volume30Day decimal.Decimal `json:"volume_30day"`
}

ProductStats represents a 24 hr stat for the product. Volume is in base currency units. Open, High, Low are in quote currency units.

type ProductStatus

type ProductStatus string

ProductStatus has little documentation; all sandbox products have a status value of `online`

type ProductTicker

type ProductTicker struct {
	Ask     decimal.Decimal `json:"ask"`
	Bid     decimal.Decimal `json:"bid"`
	Price   decimal.Decimal `json:"price"`
	Size    decimal.Decimal `json:"size"`
	TradeID int             `json:"trade_id"`
	Time    Time            `json:"time"`
	Volume  decimal.Decimal `json:"volume"`
}

ProductTicker holds snapshot information about the last trade (tick), best bid/ask and 24h volume.

type ProductTrade

type ProductTrade struct {
	Price   decimal.Decimal `json:"price"`
	Side    Side            `json:"side"`
	Size    decimal.Decimal `json:"size"`
	Time    Time            `json:"time"`
	TradeID int             `json:"trade_id"`
}

type ProductTrades

type ProductTrades struct {
	Trades []*ProductTrade `json:"trades"`
	Page   *Pagination     `json:"page"`
}

ProductTrades represents the latest trades for a product

func (*ProductTrades) UnmarshalJSON

func (p *ProductTrades) UnmarshalJSON(b []byte) error

type Profile

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

type ProfileFilter

type ProfileFilter struct {
	Active bool `json:"active"`
}

func (ProfileFilter) Params

func (p ProfileFilter) Params() []string

type ProfileTransfer

type ProfileTransfer struct {
	Amount   decimal.Decimal `json:"amount"`
	Currency CurrencyName    `json:"currency"`
	From     string          `json:"from"`
	To       string          `json:"to"`
}

type ProfileTransferSpec

type ProfileTransferSpec struct {
	Amount   decimal.Decimal `json:"amount"`
	Currency CurrencyName    `json:"currency"`
	From     string          `json:"from"`
	To       string          `json:"to"`
}

func (*ProfileTransferSpec) UnmarshalJSON

func (p *ProfileTransferSpec) UnmarshalJSON(b []byte) error

type Report

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

type ReportDateRange

type ReportDateRange struct {
	EndDate   Time `json:"end_date"`
	StartDate Time `json:"start_date"`
}

type ReportFormat

type ReportFormat string
const (
	ReportFormatCSV ReportFormat = "csv"
	ReportFormatPDF ReportFormat = "pdf" // default
)

type ReportSpec

type ReportSpec struct {
	AccountID string       `json:"account_id"`
	EndDate   Time         `json:"end_date"`
	Email     string       `json:"email"`
	Format    ReportFormat `json:"format"`
	ProductID ProductID    `json:"product_id"`
	StartDate Time         `json:"start_date"`
	Type      ReportType   `json:"type"`
}

func (*ReportSpec) UnmarshalJSON

func (c *ReportSpec) UnmarshalJSON(b []byte) error

func (*ReportSpec) Validate

func (c *ReportSpec) Validate() error

type ReportStatus

type ReportStatus string
const (
	// ReportStatusCreating indicates that report is being created
	ReportStatusCreating ReportStatus = "creating"
	// ReportStatusPending indicates that the report request has been accepted and is awaiting processing
	ReportStatusPending ReportStatus = "pending"
	// ReportStatusReady indicates that the report is ready for download from `file_url`
	ReportStatusReady ReportStatus = "ready"
)

type ReportType

type ReportType string
const (
	ReportTypeAccount ReportType = "account"
	ReportTypeFills   ReportType = "fills"
)

type SEPADepositInformation

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

type SelfTrade

type SelfTrade string
const (
	// SelfTradeDecrementAndCancel is the default behavior. When two orders from the same user cross, the smaller order
	// will be canceled and the larger order size will be decremented by the smaller order size.
	// If the two orders are the same size, both will be canceled.
	SelfTradeDecrementAndCancel SelfTrade = "dc"
	// SelfTradeCancelNewest cancels the newer (taking) order in full. The old resting order remains on the order book.
	SelfTradeCancelNewest SelfTrade = "cn"
	// SelfTradeCancelOldest cancels the older (resting) order in full. The new order continues to execute.
	SelfTradeCancelOldest SelfTrade = "co"
	// SelfTradeCancelBoth immediately cancels both orders.
	SelfTradeCancelBoth SelfTrade = "cb"
)

func (*SelfTrade) UnmarshalJSON

func (s *SelfTrade) UnmarshalJSON(b []byte) error

func (SelfTrade) Validate

func (s SelfTrade) Validate() error

type ServerTime

type ServerTime struct {
	ISO   time.Time       `json:"iso"`
	Epoch decimal.Decimal `json:"epoch"`
}

type Side

type Side string
const (
	SideBuy  Side = "buy"
	SideSell Side = "sell"
)

func (Side) Validate

func (s Side) Validate() error

type StablecoinConversion

type StablecoinConversion struct {
	Amount        decimal.Decimal `json:"amount"`
	From          CurrencyName    `json:"from"`
	FromAccountID string          `json:"from_account_id"`
	ID            string          `json:"id"`
	To            CurrencyName    `json:"to"`
	ToAccountID   string          `json:"to_account_id"`
}

type StablecoinConversionSpec

type StablecoinConversionSpec struct {
	From   CurrencyName    `json:"from"`
	To     CurrencyName    `json:"to"`
	Amount decimal.Decimal `json:"amount"`
}

func (*StablecoinConversionSpec) UnmarshalJSON

func (s *StablecoinConversionSpec) UnmarshalJSON(b []byte) error

type Stop

type Stop string

Stop orders become active and wait to trigger based on the movement of the last trade price. There are two types of triggered Stop, StopLoss and StopEntry: StopEntry triggers when the last trade price changes to a value at or above the StopPrice. StopLoss triggers when the last trade price changes to a value at or below the StopPrice. The last trade price is the last price at which an order was filled. This price can be found in the latest match message. Note that not all match messages may be received due to dropped messages.

const (
	// StopEntry triggers when the last trade price changes to a value at or above the StopPrice.
	StopEntry Stop = "entry"
	// StopLoss triggers when the last trade price changes to a value at or below the StopPrice.
	StopLoss Stop = "loss"
	// StopNone is the default Stop. A LimitOrder with StopNone will be booked immediately when created.
	StopNone Stop = ""
)

func (Stop) Validate

func (s Stop) Validate() error

func (Stop) ValidatePrice

func (s Stop) ValidatePrice(price *decimal.Decimal) error

type SubscriptionRequest

type SubscriptionRequest struct {
	Type       MessageType   `json:"type"` // must be 'subscribe'
	ProductIDs []ProductID   `json:"product_ids"`
	Channels   []interface{} `json:"channels"`
}

A SubscriptionRequest describes the products and channels to be provided by the feed.

func NewSubscriptionRequest

func NewSubscriptionRequest(productIDs []ProductID, channelNames []ChannelName, productChannels []Channel) SubscriptionRequest

NewSubscriptionRequest creates the initial message to the server indicating which channels and products to receive. This message is mandatory — you will be disconnected if no subscribe has been received within 5 seconds.

There are two ways to specify products to listen for within each channel: - By specifying a list of products for all subscribed channels - By specifying the product ids for an individual channel

Both mechanisms can be used together in a single subscription request.

type Time

type Time time.Time

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON marshal time back to time.Time for json encoding

func (*Time) Time

func (t *Time) Time() time.Time

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

type TimeInForce

type TimeInForce string

TimeInForce 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.

const (
	// TimeInForceGoodTillCanceled orders remain open on the book until canceled. Default.
	TimeInForceGoodTillCanceled TimeInForce = "GTC"
	// TimeInForceGoodTillTime orders remain open on the book until canceled or the allotted CancelAfter has passed.
	// After the CancelAfter timestamp is passed, GTT orders are guaranteed to cancel before any other order is processed.
	// Note that a "day" is considered 24 hours.
	TimeInForceGoodTillTime TimeInForce = "GTT"
	// TimeInForceImmediateOrCancel orders instantly cancel the remaining size of the limit order instead of opening it on the book.
	TimeInForceImmediateOrCancel TimeInForce = "IOC"
	// TimeInForceFillOrKill are rejected if the entire size cannot be matched.
	TimeInForceFillOrKill TimeInForce = "FOK"
)

func (TimeInForce) Validate

func (t TimeInForce) Validate() error

func (TimeInForce) ValidateCancelAfter

func (t TimeInForce) ValidateCancelAfter(cancelAfter string) error

type Timeslice

type Timeslice int
const (
	Timeslice1Minute   Timeslice = 60
	Timeslice5Minutes  Timeslice = 300
	Timeslice15Minutes Timeslice = 900
	Timeslice1Hour     Timeslice = 3600
	Timeslice6Hours    Timeslice = 21600
	Timeslice1Day      Timeslice = 86400
)

func (Timeslice) Valid

func (t Timeslice) Valid() error

type TimesliceParam

type TimesliceParam time.Duration

func (TimesliceParam) Timeslice

func (t TimesliceParam) Timeslice() Timeslice

func (*TimesliceParam) UnmarshalJSON

func (t *TimesliceParam) UnmarshalJSON(b []byte) error

func (TimesliceParam) Validate

func (t TimesliceParam) Validate() error

type WireDepositInformation

type WireDepositInformation struct {
	Code           string  `json:"code"`
	Name           string  `json:"name"`
	AccountAddress string  `json:"account_address"`
	AccountName    string  `json:"account_name"`
	AccountNumber  string  `json:"account_number"`
	BankAddress    string  `json:"bank_address"`
	BankCountry    Country `json:"bank_country"`
	Reference      string  `json:"reference"`
	RoutingNumber  string  `json:"routing_number"`
}

type Withdrawal

type Withdrawal struct {
	// Details provides more fine-grained information describing the Withdrawal
	Details WithdrawalDetails `json:"details"`
	// CanceledAt is the time of cancellation, if the Withdrawal was canceled
	CanceledAt *Time `json:"canceled_at"`
	// CompletedAt is the time of completion, if the Withdrawal was completed
	CompletedAt *Time `json:"completed_at"`
	// CreatedAt is the time of creation
	CreatedAt Time `json:"created_at"`
	// CreatedAt is the time the transfer was processed
	ProcessedAt *Time `json:"processed_at"`
	// AccountID identifies the Account to which the Withdrawal applies
	AccountID string `json:"account_id"`
	// Amount is the amount of the Withdrawal
	// TODO: in what currency?
	Amount   decimal.Decimal `json:"amount"`
	Currency CurrencyName    `json:"currency"`
	ID       string          `json:"id"`
	// Type identifies the type of the Withdrawal (`withdraw` or `internal_withdraw`)
	Type WithdrawalType `json:"type"`
	// UserID that initiated the Withdrawal
	UserID    string `json:"user_id"`
	UserNonce string `json:"user_nonce"`
}

Withdrawal represents a movement of CurrencyName out of accounts to both external and internal destinations. Withdrawals are implemented as Transfers, but I assume this was confusing/naive, as the documentation rebrands Transfers as Withdrawals. I have followed the hint and done the same.

type WithdrawalCancelCode

type WithdrawalCancelCode int
const (
	WithdrawalCancelCodeDefaultError                             WithdrawalCancelCode = 0
	WithdrawalCancelCodeMaxExceeded                              WithdrawalCancelCode = 1000
	WithdrawalCancelCodeZeroAmount                               WithdrawalCancelCode = 1001
	WithdrawalCancelCodeAccountNotAllowed                        WithdrawalCancelCode = 1002
	WithdrawalCancelCodePaymentMethodNotAllowed                  WithdrawalCancelCode = 1003
	WithdrawalCancelCodeCurrencyAndPaymentMethodNotAllowed       WithdrawalCancelCode = 1004
	WithdrawalCancelCodeAmountExceedsAccountFunds                WithdrawalCancelCode = 1005
	WithdrawalCancelCodeAmountMustBeAtLeastOne                   WithdrawalCancelCode = 1006
	WithdrawalCancelCodeAmountTooSmall                           WithdrawalCancelCode = 1007
	WithdrawalCancelCodeNoRecurringTransfersWithPaymentMethod    WithdrawalCancelCode = 1008
	WithdrawalCancelCodeCurrencyDoesNotMatchAccountCurrency      WithdrawalCancelCode = 1009
	WithdrawalCancelCodePaymentMethodUnsupported                 WithdrawalCancelCode = 1010
	WithdrawalCancelCodeWithdrawalRateLimitExceeded              WithdrawalCancelCode = 1011
	WithdrawalCancelCodeAmountExceedsMaximumAccountBalance       WithdrawalCancelCode = 1012
	WithdrawalCancelCodeNegativeAmount                           WithdrawalCancelCode = 1013
	WithdrawalCancelCodeNoTagNameProvided                        WithdrawalCancelCode = 2000
	WithdrawalCancelCodeAmountExceedsSendLimits                  WithdrawalCancelCode = 2004
	WithdrawalCancelCodeMaxSendsExceeded                         WithdrawalCancelCode = 2005
	WithdrawalCancelCodeSendAmountTooSmallForOnBlockchain        WithdrawalCancelCode = 2007
	WithdrawalCancelCodeTwoStepVerificationCodeRequired          WithdrawalCancelCode = 2008
	WithdrawalCancelCodeCurrencyRequiresTagName                  WithdrawalCancelCode = 2009
	WithdrawalCancelCodeInvalidAmount                            WithdrawalCancelCode = 2010
	WithdrawalCancelCodeCurrencyTemporarilyDisabled              WithdrawalCancelCode = 2011
	WithdrawalCancelCodeAmountExceedsCurrencyMaxWithdrawalAmount WithdrawalCancelCode = 2012
	WithdrawalCancelCodeAmountExceedsCurrencyMaxSendAmount       WithdrawalCancelCode = 2013
	WithdrawalCancelCodeSendFromFiatAccountsTemporarilyDisabled  WithdrawalCancelCode = 2014
	WithdrawalCancelCodePaymentRequestExpired                    WithdrawalCancelCode = 2015
	WithdrawalCancelCodeSendFromAccountNotAllowed                WithdrawalCancelCode = 2016
	WithdrawalCancelCodeUnableToSendToAddress                    WithdrawalCancelCode = 2017
	WithdrawalCancelCodeRecipientAddressNotWhitelisted           WithdrawalCancelCode = 2018
	WithdrawalCancelCodeRecipientAddressWhitelistPending         WithdrawalCancelCode = 2020
	WithdrawalCancelCodeUnableToSendToUser                       WithdrawalCancelCode = 2021
	WithdrawalCancelCodeUnableToSendToSelf                       WithdrawalCancelCode = 2022
	WithdrawalCancelCodeSendRateExceeded                         WithdrawalCancelCode = 2023
	WithdrawalCancelCodeInvalidEmailOrNetworkAddress             WithdrawalCancelCode = 2024
	WithdrawalCancelCodeAccountDoesNotSupportCurrency            WithdrawalCancelCode = 2025
)

1xxx cancel codes are for fiat transfers and 2xxx cancel codes are for crypto transfer. Please make changes accordingly before retrying the withdrawal.

func (WithdrawalCancelCode) String

func (w WithdrawalCancelCode) String() string

type WithdrawalDetails

type WithdrawalDetails map[string]interface{}

WithdrawalDetails is not well documented; until proven or requested otherwise, I will simply treat the details as free form annotations or labels.

type WithdrawalFeeEstimate

type WithdrawalFeeEstimate struct {
	Fee decimal.Decimal `json:"fee"`
}

type WithdrawalFilter

type WithdrawalFilter struct {
	// ProfileID limits the list of Withdrawals to the ProfileID. By default, Withdrawals retrieves Withdrawals for the default profile.
	ProfileID string `json:"profile_id"`
	// Type identifies the type of the Withdrawal (`withdraw` or `internal_withdraw`)
	Type WithdrawalType `json:"type"`
}

func (WithdrawalFilter) Params

func (d WithdrawalFilter) Params() []string

type WithdrawalType

type WithdrawalType string
const (
	WithdrawalTypeWithdraw WithdrawalType = "withdraw"
	WithdrawalTypeInternal WithdrawalType = "internal_withdraw"
)

type Withdrawals

type Withdrawals struct {
	Withdrawals []*Withdrawal `json:"withdrawals"`
	Page        *Pagination   `json:"page"`
}

func (*Withdrawals) UnmarshalJSON

func (w *Withdrawals) UnmarshalJSON(b []byte) error

Jump to

Keyboard shortcuts

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