coinbase

package module
v0.0.0-...-06d75bf Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2024 License: AGPL-3.0 Imports: 23 Imported by: 0

README

go-coinbase

Go SDK for Coinbase's v3 Advanced Trade REST API

This does not include the Advanced Trade WebSocket.

Installation

go-coinbase is compatible with Go releases in module mode:

go get github.com/justinsimmons/go-coinbase

Usage

    import "github.com/justinsimmons/go-coinbase"

Alternatively you can use an alias to shorten the invocation.

    import cb "github.com/justinsimmons/go-coinbase"

Construct a new Coinbase client, then use the various services on the client to access different parts of the Advanced Trade REST API. For example:

client := coinbase.NewWithCloud("api-key", "api-secret")

// List all accounts for the user.
accounts, err := client.Accounts.List(context.Background(), nil)

Some APIs have optional parameters that can be passed:

client := coinbase.NewWithCloud("api-key", "api-secret")

// Will filter the orders response to only return a specific product.
opt := &ListOrdersOptions{ProductID: coinbase.String("BTC-USD")}

// Gets a list of orders that can be filterd with filtered by optional parameters.
orders, err := client.Orders.List(context.Background(), opt)

The services of a client divide the API into logical chunks and correspond to the structure of the Advanced Trade REST API documentation at: https://docs.cloud.coinbase.com/advanced-trade-api/docs/welcome .

NOTE: Using the context package, one can easily pass cancelation signals and deadlines to various services of the client for handling a request. In case there is no context available, then context.Background() can be used as a starting point.

Supported APIs

API Description Supported
List Accounts Get a list of authenticated accounts for the current user.
Get Account Get a list of information about an account, given an account UUID.
Create Order Create an order with a specified product_id (asset-pair), side (buy/sell), etc.
Cancel Orders Initiate cancel requests for one or more orders.
Edit Order Edit an order with a specified new size, or new price.
Edit Order Preview Simulate an edit order request with a specified new size, or new price, to preview the result of an edit. Only limit order types, with time in force type of good-till-cancelled can be edited.
List Orders Get a list of orders filtered by optional query parameters (product_id, order_status, etc).
List Fills Get a list of fills filtered by optional query parameters (product_id, order_id, etc).
Get Order Get a single order by order ID.
Get Best Bid/Ask Get the best bid/ask for all products. A subset of all products can be returned instead by using the product_ids input.
Get Product Book Get a list of bids/asks for a single product. The amount of detail shown can be customized with the limit parameter.
List Products Get a list of the available currency pairs for trading.
Get Product Get information on a single product by product ID.
Get Product Candles Get rates for a single product by product ID, grouped in buckets.
Get Market Trades Get snapshot information, by product ID, about the last trades (ticks), best bid/ask, and 24h volume.
List Portfolios Get a list of all portfolios of a user.
Create Portfolio Create a portfolio.
Move Portfolio Funds Transfer funds between portfolios.
Get Portfolio Breakdown Get the breakdown of a portfolio by portfolio ID.
Delete Portfolio Delete a portfolio by portfolio ID.
Edit Portfolio Modify a portfolio by portfolio ID.
Get Futures Balance Summary Get information on your balances related to Coinbase Financial Markets (CFM) futures trading.
List Futures Positions Get a list of all open positions in CFM futures products.
Get Futures Position Get the position of a specific CFM futures product.
Schedule Futures Sweep Schedule a sweep of funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.
List Futures Sweeps Get information on your pending and/or processing requests to sweep funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.
Cancel Pending Futures Sweep Cancel your pending sweep of funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.
Get Transactions Summary Get a summary of transactions with fee tiers, total volume, and fees.
Create Convert Quote Create a convert quote with a specified source currency, target currency, and amount.
Commit Convert Trade Commits a convert trade with a specified trade ID, source currency, and target currency.
Get Convert Trade Gets a list of information about a convert trade with a specified trade ID, source currency, and target currency.
Get Unix Time Get the current time from the Coinbase Advanced API.
Allocate Portfolio Allocate more funds to an isolated position in your Perpetuals portfolio.

✅ = Implemented and fully tested. ⚠️ = Implemented but not able to test. ❌ = Not implemented but on roadmap.

Authentication

Coinbase has multiple authentication schemes available for different APIs. For information on which scheme you should use please consult the docs.

I would recommend you use cloud API trading keys as they allow for the full functionality of the advance trade APIs.

The following is the compatibility list for the available authentication schemes with go-coinbase.

Scheme Supported
Cloud API Trading keys
OAuth ⚠️
Legacy API Keys
Cloud API Trading Keys

Coinbase Cloud supports two API key types, "Trading" keys and "General" keys. The Advanced API is only compatible with Cloud API Trading keys.

Instructions on generating a cloud API trading key.

Generate a client with Cloud API Trading credentials:

// Please don't actually hard code these, pass them in via flag.
const (
    apiKey = "organizations/{org_id}/apiKeys/{key_id}"
    apiSecret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"
)

// All API requests will use cloud API trading credentials.
client := coinbase.NewWithCloud(apiKey, apiSecret)
Legacy API Keys

Note that the legacy api keys do not suport any of the newer functionality of the Advanced Trade API (Portfolios, etc.).

Instructions on generating a legacy api key.

Generate a client with legacy credentials:

// All API requests will use legacy API credentials.
client := coinbase.NewWithLegacy("api-key", "api-secret")
OAuth

The OAuth authentication scheme is for applications serving many users, which is outside my use case for this package. To use this authentication scheme you are going to need to implement a custom authentication scheme.

Custom Authentication Scheme

If for whatever reason you would like to use your own authentication method for the API requests you need not rely on the prebuilt functionality provided by this client. You may implem

  1. Implement the coinbase.Authenticator interface. Example:

    type customAuthenticator struct {
        token string
    }
    
    // customAuthenticator implements coinbase.Authenticator interface.
    func (a customAuthenticator) Authenticate(r *http.Request) error {
        r.Header.Set("Authorization", "Bearer " + a.token)
    
        return nil
    }
    
  2. Inject it into the client with the option coinbase.WithCustomAuthenticator().

    token := "foo"
    authenticator := customAuthenticator{token: token}
    
    // Inject custom authenticator into the client.
    client := client.New(coinbase.WithCustomAuthenticator(authenticator))
    
    // Headers will now have a {"Authentication": {"Bearer foo"}} entry.
    orders, err := client.Orders.List(context.Background(), opt)
    

Rate Limits

Advanced Trade API endpoints are throttled by user at 30 requests per second.

Learn more about Coinbase rate limiting at https://docs.cloud.coinbase.com/advanced-trade-api/docs/rest-api-rate-limits .

Order Management

The maximum number of OPEN orders allowed per product_id is 500. If you have 500 open orders for a product_id at submission, new orders placed for that product immediately enter a failed state.

Advanced API Order Management

Coinbase Pro

Coinbase Pro has been disabled for use and all customers have been migrated as of December 1, 2023. This was accelerated from a prior announcement of Pro deprecation in 2024.

You cannot use existing Pro API keys to trade with Advanced Trade. See Migrating from Pro.

License

Copyright 2024 Justin Simmons.

This program is released under the GNU Affero General Public License v3 or later.

Documentation

Overview

Coinbase Advanced Trade API SDK for Golang.

Source code available at: https://github.com/justinsimmons/go-coinbase

The Advanced Trade API (or Advanced API) supports programmatic trading and order management with a REST API and WebSocket protocol for real-time market data. REST API documentation: https://docs.cloud.coinbase.com/advanced-trade-api/docs/rest-api-overview Web Socket protocol: https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview

Coinbase Advanced replaced Coinbase Pro as the "advanced" trading platform. The Coinbase Advanced API lets you manage orders, products, and fees with the new v3 endpoints. It does not duplicate core Coinbase functions for account deposits, withdrawals, and transactions. The Coinbase Advanced REST API supports advanced trading features only.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnexpectedAPIResponse = errors.New("coinbase API returned a response outside the API documetation")

ErrUnexpectedAPIResponse - coinbase API returned a response outside the API documetation.

Functions

func Bool

func Bool(v bool) *bool

Bool is a helper function that allocates a new bool value to store v and returns a pointer to it.

func Int

func Int(v int) *int

Int is a helper function that allocates a new int value to store v and returns a pointer to it.

func Int64

func Int64(v int64) *int64

Int64 is a helper function that allocates a new int64 value to store v and returns a pointer to it.

func String

func String(v string) *string

String is a helper function that allocates a new string value to store v and returns a pointer to it.

func Time

func Time(v time.Time) *time.Time

Time is a helper function that allocates a new time value to store v and returns a pointer to it.

func WithBaseURL

func WithBaseURL(url string) func(*Client)

WithBaseURL overrides the base URL of the Advanced Trade REST API on the client.

func WithCustomAuthenticator

func WithCustomAuthenticator(authenticator Authenticator) func(*Client)

WithCustomAuthenticator allows the caller to provide custom authentication schema to the client. This is useful to hook into the HTTP request and modify it as desired before it is executed.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) func(*Client)

WithHTTPClient overrides the default HTTP client used by the client.

Types

type Account

type Account struct {
	ID               *uuid.UUID       `json:"uuid"`              // Unique identifier for account.
	Name             *string          `json:"name"`              // Name for the account.
	Currency         *string          `json:"currency"`          // Currency symbol for the account.
	AvailableBalance AvailableBalance `json:"available_balance"` // Available balance of account.
	Default          *bool            `json:"default"`           // Whether or not this account is the user's primary account.
	Active           *bool            `json:"active"`            // Whether or not this account is active and okay to use.
	CreatedAt        *time.Time       `json:"created_at"`        // Time at which this account was created.
	UpdatedAt        *time.Time       `json:"updated_at"`        // Time at which this account was updated.
	DeletedAt        *time.Time       `json:"deleted_at"`        // Time at which this account was deleted.
	Type             *AccountType     `json:"type"`              // Type of account.
	Ready            *bool            `json:"ready"`             // Whether or not this account is ready to trade.
	Hold             Hold             `json:"hold"`
}

Coinabase account metadata.

type AccountListOptions

type AccountListOptions struct {
	// A pagination limit with default of 49 and maximum of 250.
	// If has_next is true, additional orders are available to be fetched with pagination and the cursor value
	// in the response can be passed as cursor parameter in the subsequent request.
	Limit *int32 `url:"limit,omitempty"`
	// Cursor used for pagination. When provided, the response returns responses after this cursor.
	Cursor *string `url:"cursor,omitempty"`
}

type AccountService

type AccountService service

func (*AccountService) Get

func (s *AccountService) Get(ctx context.Context, id string) (*Account, error)

Get retrieves a list of information about an account, given an account UUID.

func (*AccountService) List

List retrieves a list of authenticated accounts for the current user. https://docs.cloud.coinbase.com/advanced-trade-api/reference/retailbrokerageapi_getaccounts

type AccountType

type AccountType string

Type of coinbase account.

const (
	AccountTypeUnspecified AccountType = "UNSPECIFIED"
	AccountTypeCrypto      AccountType = "ACCOUNT_TYPE_CRYPTO"
	AccountTypeFiat        AccountType = "ACCOUNT_TYPE_FIAT"
	AccountTypeVault       AccountType = "ACCOUNT_TYPE_VAULT"
)

type AllocatePortfolioOptions

type AllocatePortfolioOptions struct {
	PortfolioUUID uuid.UUID `json:"portfolio_uuid"` // The unique identifier for the perpetuals portfolio.
	Symbol        string    `json:"symbol"`         // The product_id for which funds must be allocated.
	Amount        string    `json:"amount"`         // The value of funds to be allocated for a specific isolated position.
	Currency      string    `json:"currency"`       // The currency of funds to be allocated for a specific isolated position.
}

type Authenticator

type Authenticator interface {
	Authenticate(*http.Request) error
}

Authenticator adds authentication details to each HTTP request made from the client.

type AvailableBalance

type AvailableBalance struct {
	Value    string `json:"value"`    // Amount of currency that this object represents.
	Currency string `json:"currency"` // Denomination of the currency.
}

Available balance belonging to coinbase account.

type BalanceSummary

type BalanceSummary struct {
	FuturesBuyingPower          Funds `json:"futures_buying_power"`          // The amount of your cash balance that is available to trade CFM futures.
	TotalBalance                Funds `json:"total_usd_balance"`             // Aggregate USD maintained across your CFTC-regulated futures account and your Coinbase Inc. spot account
	CBIBalance                  Funds `json:"cbi_usd_balance"`               // USD maintained in your Coinbase Inc. spot account.
	CFMBalance                  Funds `json:"cfm_usd_balance"`               // USD maintained in your CFTC-regulated futures account. Funds held in your futures account are not available to trade spot.
	TotalOpenOrdersHoldAmmount  Funds `json:"total_open_orders_hold_amount"` // Your total balance on hold for spot and futures open orders.
	UnrealizedPNL               Funds `json:"unrealized_pnl"`                // Your current unrealized PnL across all open positions.
	DailyRealizedPNL            Funds `json:"daily_realized_pnl"`            // Your realized PnL from the current trade date. May include profit or loss from positions you’ve closed on the current trade date.
	InitialMargin               Funds `json:"initial_margin"`                // Margin required to initiate futures positions. Once futures orders are placed, these funds cannot be used to trade spot. The actual amount of funds necessary to support executed futures orders will be moved to your futures account.
	AvailableMargin             Funds `json:"available_margin"`              // Funds available to meet your anticipated margin requirement. This includes your CBI spot USD, CFM futures USD, and Futures PnL, less any holds for open spot or futures orders.
	LiquidationThreshold        Funds `json:"liquidation_threshold"`         // When your available funds for collateral drop to the liquidation threshold, some or all of your futures positions will be liquidated.
	LiquidationBufferAmount     Funds `json:"liquidation_buffer_amount"`     // Funds available in excess of the liquidation threshold, calculated as available margin minus liquidation threshold. If your liquidation buffer amount reaches 0, your futures positions and/or open orders will be liquidated as necessary.
	LiquidationBufferPercentage Funds `json:"liquidation_buffer_percentage"` // Funds available in excess of the liquidation threshold expressed as a percentage. If your liquidation buffer percentage reaches 0%, your futures positions and/or open orders will be liquidated as necessary.
}

type BidAsk

type BidAsk struct {
	Price *string `json:"price"`
	Size  *string `json:"size"`
}

type CancelOrderFailureReason

type CancelOrderFailureReason string
const (
	CancelOrderFailureReasonUnknown          CancelOrderFailureReason = "UNKNOWN_CANCEL_FAILURE_REASON"
	CancelOrderFailureReasonInvalidRequest   CancelOrderFailureReason = "INVALID_CANCEL_REQUEST"
	CancelOrderFailureReasonUnknownOrder     CancelOrderFailureReason = "UNKNOWN_CANCEL_ORDER"
	CancelOrderFailureReasonRejectedOrder    CancelOrderFailureReason = "COMMANDER_REJECTED_CANCEL_ORDER"
	CancelOrderFailureReasonDuplicateRequest CancelOrderFailureReason = "DUPLICATE_CANCEL_REQUEST"
)

type CancelledOrder

type CancelledOrder struct {
	Success       bool                      `json:"success"` // Whether the cancel request was submitted successfully.
	FailureReason *CancelOrderFailureReason `json:"failure_reason"`
	ID            string                    `json:"order_id"` // The IDs of order cancel request was initiated for.
}

type Candles

type Candles struct {
	Start  *string `json:"start"`  // Timestamp for bucket start time, in UNIX time.
	Low    *string `json:"low"`    // Lowest price during the bucket interval.
	High   *string `json:"high"`   // Highest price during the bucket interval.
	Open   *string `json:"open"`   // Opening price (first trade) in the bucket interval.
	Close  *string `json:"close"`  // Closing price (last trade) in the bucket interval.
	Volume *string `json:"volume"` // Volume of trading activity during the bucket interval.
}

type Client

type Client struct {
	Accounts  *AccountService    // Interface with the Advanced Trade REST API Accounts APIs.
	Orders    *OrdersService     // Interface with the Advanced Trade REST API Orders APIs.
	Products  *ProductsService   // Interface with the Advanced Trade REST API Products API.
	Fees      *FeesService       // Interface with the Advanced Trade REST API Fees API.
	Portfolio *PortfoliosService // Interface with the Advanced Trade REST API Portfolios API.
	Futures   *FuturesService    // Interface with the Advanced Trade REST API Futures API.
	Common    *CommonService     // Interface with the Advanced Trade REST API Common API.
	// contains filtered or unexported fields
}

Coinbase Advanced Trade REST API client.

func New

func New(opts ...option) *Client

New creates a new Coinbase Advanced Trade REST API client. By default no authentication schema has been added. Coinbase will block any unauthenticated requests.

  • To use Legacy API key authentication prefer NewWithLegacy()
  • To use Cloud API Trading Key authentication prefer NewWithCloud()
  • To use a custom authentication schema use the WithCustomAuthenticator option as an argument to this method.

func NewWithCloud

func NewWithCloud(apiKey string, apiSecret string, opts ...option) (*Client, error)

New creates a new Coinbase Advanced Trade REST API client, using Cloud API Trading Keys for authentication.

func NewWithLegacy

func NewWithLegacy(apiKey string, apiSecret string, opts ...option) *Client

New creates a new Coinbase Advanced Trade REST API client, using legacy API key authentication. Please note some of he newer endpoints will not work unless you use the new Cloud API Trading Keys.

type CoinbaseError

type CoinbaseError struct {
	Err     *string        `json:"error"`
	Code    *int32         `json:"code"`
	Message *string        `json:"message"`
	Details []ErrorDetails `json:"details"`
}

Detault error returned by the coinbase API.

func (CoinbaseError) Error

func (e CoinbaseError) Error() string

func (CoinbaseError) GetCode

func (e CoinbaseError) GetCode() int

func (CoinbaseError) GetMessage

func (e CoinbaseError) GetMessage() string

type CoinbaseUnixTime

type CoinbaseUnixTime struct {
	ISO          *string `json:"iso"`          // An ISO-8601 representation of the timestamp.
	EpochSeconds *string `json:"epochSeconds"` // A second-precision representation of the timestamp.
	EpochMillis  *string `json:"epochMillis"`  // A millisecond-precision representation of the timestamp.
}

func (CoinbaseUnixTime) UnixMilli

func (ut CoinbaseUnixTime) UnixMilli() (time.Time, error)

UnixMilli returns the local Time corresponding to the given Unix time, msec milliseconds since January 1, 1970 UTC.

type CommonService

type CommonService service

func (*CommonService) GetUnixTime

func (s *CommonService) GetUnixTime(ctx context.Context) (*CoinbaseUnixTime, error)

GetUnixTime gets the current time from the Coinbase Advanced API.

type ContractExpiryType

type ContractExpiryType string
const (
	ContractExpiryTypeUnknown   ContractExpiryType = "UNKNOWN_CONTRACT_EXPIRY_TYPE"
	ContractExpiryTypeExpiring  ContractExpiryType = "EXPIRING"
	ContractExpiryTypePerpetual ContractExpiryType = "PERPETUAL"
)

type CreateOrderErrorMetadata

type CreateOrderErrorMetadata struct {
	Error                 *OrderFailureReason   `json:"error"`
	Message               *string               `json:"message"`       // Generic error message explaining why the order was not created.
	ErrorDetails          *string               `json:"error_details"` // Descriptive error message explaining why the order was not created.
	PreviewFailureReason  *PreviewFailureReason `json:"preview_failure_reason"`
	NewOrderFailureReason *OrderFailureReason   `json:"new_order_failure_reason"`
}

type CreateOrderOptions

type CreateOrderOptions struct {
	ClientOrderID         string             `json:"client_order_id"`          // A unique ID provided by the client for their own identification purposes. This ID differs from the order_id generated for the order. If the ID provided is not unique, the order fails to be created and the order corresponding to that ID is returned.
	ProductID             string             `json:"product_id"`               // The product this order was created for e.g. 'BTC-USD'.
	Side                  *Side              `json:"side"`                     // Possible values: [BUY, SELL].
	OrderConfiguration    OrderConfiguration `json:"order_configuration"`      // Configuration of the order details.
	SelfTradePreventionID *string            `json:"self_trade_prevention_id"` // Self trade prevention ID, to prevent an order crossing against the same user.
	Leverage              *string            `json:"leverage"`                 // Leverage for this order; default value is "1.0".
	MarginType            *MarginType        `json:"margin_type"`              // Side the order is on (BUY, SELL).
	RetailPortfolioID     *string            `json:"retail_portfolio_id"`      // Retail portfolio uuid, to associate this order with a retail portfolio.
}

type CreateOrderResponse

type CreateOrderResponse struct {
	Success            bool                       `json:"success"`        // Whether the order was created.
	OrderFailureReason *OrderFailureReason        `json:"failure_reason"` // Reason for order failure if failure occurs.
	OrderID            *string                    `json:"order_id"`       // The ID of the order created.
	SuccessResponse    CreateOrderSuccessMetadata `json:"success_response"`
	ErrorResponse      CreateOrderErrorMetadata   `json:"error_response"`
	OrderConfiguration *OrderConfiguration        `json:"order_configuration"`
}

type CreateOrderSuccessMetadata

type CreateOrderSuccessMetadata struct {
	OrderID       string  `json:"order_id"`        // The ID of the order created.
	ProductID     *string `json:"product_id"`      // The product this order was created for e.g. 'BTC-USD'.
	Side          *Side   `json:"side"`            // Possible values: [BUY, SELL].
	ClientOrderID *string `json:"client_order_id"` // Client specified ID of order.
}

type EditFailureReason

type EditFailureReason string
const (
	EditFailureReasonUnknown                      EditFailureReason = "UNKNOWN_EDIT_ORDER_FAILURE_REASON"
	EditFailureReasonRejectedEditOrder            EditFailureReason = "COMMANDER_REJECTED_EDIT_ORDER"
	EditFailureReasonBelowFilledSize              EditFailureReason = "CANNOT_EDIT_TO_BELOW_FILLED_SIZE"
	EditFailureReasonNotFound                     EditFailureReason = "ORDER_NOT_FOUND"
	EditFailureReasonCallerIdMismatch             EditFailureReason = "CALLER_ID_MISMATCH"
	EditFailureReasonOnlyLimitOrderEditsSupported EditFailureReason = "ONLY_LIMIT_ORDER_EDITS_SUPPORTED"
	EditFailureReasonInvalidEditedSize            EditFailureReason = "INVALID_EDITED_SIZE"
	EditFailureReasonInvalidEditedPrice           EditFailureReason = "INVALID_EDITED_PRICE"
	EditFailureReasonInvalidOriginalSize          EditFailureReason = "INVALID_ORIGINAL_SIZE"
	EditFailureReasonInvalidOriginalPrice         EditFailureReason = "INVALID_ORIGINAL_PRICE"
	EditFailureReasonEditEqualToOriginal          EditFailureReason = "EDIT_REQUEST_EQUAL_TO_ORIGINAL_REQUEST"
	EditFailureReasonOnlyOpenOrdersCanBeEdited    EditFailureReason = "ONLY_OPEN_ORDERS_CAN_BE_EDITED"
)

type EditOrderOptions

type EditOrderOptions struct {
	OrderID string  `json:"order_id"` // ID of order to edit.
	Price   *string `json:"price"`    // New price for order.
	Size    *string `json:"size"`     // New size for order.
}

type EditOrderResponse

type EditOrderResponse struct {
	Success bool `json:"success"` // Whether the order edit request was placed.
	Errors  []struct {
		EditFailureReason    *EditFailureReason    `json:"edit_failure_reason"`
		PreviewFailureReason *PreviewFailureReason `json:"preview_failure_reason"`
	} `json:"errors"` // Details of any errors that may have occured.
}

type EditPortfolioOptions

type EditPortfolioOptions struct {
	Name string `json:"name"`
}

type ErrorDetails

type ErrorDetails struct {
	// A URL/resource name that uniquely identifies the type of the serialized protocol buffer message.
	// This string must contain at least one "/" character.
	// The last segment of the URL's path must represent the fully qualified name of the type (as in `path/google.protobuf.Duration`).
	// The name should be in a canonical form (e.g., leading "." is not accepted).
	// In practice, teams usually precompile into the binary all types that they expect it to use in the context of Any.
	// However, for URLs which use the scheme `http`, `https`, or no scheme, one can optionally set up a type server that maps type
	// URLs to message definitions as follows: * If no scheme is provided, `https` is assumed. * An HTTP GET on the URL must yield
	// a [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results
	// based on the URL, or have them precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved o
	// n changes to types. (Use versioned type names to manage breaking changes.) Note: this functionality is not currently available in
	// the official protobuf release, and it is not used for type URLs beginning with type.googleapis.com. Schemes other than `http`, `https`
	// (or the empty scheme) might be used with implementation specific semantics.
	TypeUrl string `json:"type_url"`
	Value   byte   `json:"value"` // Must be a valid serialized protocol buffer of the above specified type.
}

type ExpiringContractStatus

type ExpiringContractStatus string
const (
	ExpiringContractStatusUnknown   ExpiringContractStatus = "UNKNOWN_EXPIRING_CONTRACT_STATUS"
	ExpiringContractStatusUnexpired ExpiringContractStatus = "STATUS_UNEXPIRED"
	ExpiringContractStatusExpired   ExpiringContractStatus = "STATUS_EXPIRED"
	ExpiringContractStatusAll       ExpiringContractStatus = "STATUS_ALL"
)

type FCMTradingSessionDetails

type FCMTradingSessionDetails struct {
	IsSessionOpen *bool      `json:"is_session_open"`
	OpenTime      *time.Time `json:"open_time"`
	CloseTime     *time.Time `json:"close_time"`
}

type FeeTier

type FeeTier struct {
	PricingTier  *string `json:"pricing_tier"`   // Pricing tier for user, determined by notional (USD) volume.
	USDFrom      *string `json:"usd_from"`       // Lower bound (inclusive) of pricing tier in notional volume.
	USDTo        *string `json:"usd_to"`         // Upper bound (exclusive) of pricing tier in notional volume.
	TakerFeeRate *string `json:"taker_fee_rate"` // Taker fee rate, applied if the order takes liquidity.
	MakerFeeRate *string `json:"maker_fee_rate"` // Maker fee rate, applied if the order creates liquidity.
	AOPFrom      *string `json:"aop_from"`       // Lower bound (inclusive) of pricing tier in usd of total assets on platform.
	AOPTO        *string `json:"aop_to"`         // Upper bound (exclusive) of pricing tier in usd of total assets on platform.
}

type FeesService

type FeesService service

func (*FeesService) GetTransactionsSummary

GetTransactionsSummary gets a summary of transactions with fee tiers, total volume, and fees.

type Fill

type Fill struct {
	EntryID            *string             `json:"entry_id"`            // Unique identifier for the fill.
	TradeID            *string             `json:"trade_id"`            // ID of the fill -- unique for all `FILL` trade_types but not unique for adjusted fills.
	OrderID            *string             `json:"order_id"`            // ID of the order the fill belongs to.
	TradeTime          *time.Time          `json:"trade_time"`          // Time at which this fill was completed.
	TradeType          *TradeType          `json:"trade_type"`          // String denoting what type of fill this is. Regular fills have the value `FILL`. Adjusted fills have possible values `REVERSAL`, `CORRECTION`, `SYNTHETIC`.
	Price              *string             `json:"price"`               // Price the fill was posted at.
	Size               *string             `json:"size"`                // Amount of order that was transacted at this fill.
	Commission         *string             `json:"commission"`          //  Fee amount for fill.
	ProductID          *string             `json:"product_id"`          // The product this order was created for.
	SequenceTimestamp  *time.Time          `json:"sequence_timestamp"`  // Time at which this fill was posted.
	LiquidityIndicator *LiquidityIndicator `json:"liquidity_indicator"` // Possible values: [UNKNOWN_LIQUIDITY_INDICATOR, MAKER, TAKER]
	SizeInQuote        *bool               `json:"size_in_quote"`       // Whether the order was placed with quote currency.
	UserID             *string             `json:"user_id"`             // User that placed the order the fill belongs to.
	Side               *Side               `json:""`                    // Side the fill is on [BUY, SELL].
}

type Funds

type Funds struct {
	Value    string `json:"value"`    // These two values fully represent the monetary amount. Non-localized amount in decimal notation (e.g. "1.234").
	Currency string `json:"currency"` // Currency symbol (USD, BTC, etc). Not an asset UUID.
}

type FutureProductDetails

type FutureProductDetails struct {
	Venue                  *string             `json:"venue"`
	ContractCode           *string             `json:"contract_code"`
	ContractExpiry         *time.Time          `json:"contract_expiry"`
	ContractSize           *string             `json:"contract_size"`
	ContractRootUnit       *string             `json:"contract_root_unit"`
	GroupDescription       *string             `json:"group_description"` // Descriptive name for the product series, eg "Nano Bitcoin Futures".
	ContractExpiryTimezone *string             `json:"contract_expiry_timezone"`
	GroupShortDescription  *string             `json:"group_short_description"` // Short version of the group_description, eg "Nano BTC".
	RiskManagedBy          *RiskManagedBy      `json:"risk_managed_by"`
	ContractExpiryType     *ContractExpiryType `json:"contract_expiry_type"`
	PerpetualDetails       *struct {
		OpenInterest *string    `json:"open_interest"`
		FundingRate  *string    `json:"funding_rate"`
		FundingTime  *time.Time `json:"funding_time"`
	} `json:"perpetual_details"`
	ContractDisplayName *string `json:"contract_display_name"`
}

type FuturesPosition

type FuturesPosition struct {
	ProductID         *string      `json:"product_id"`          // The ID of the CFM futures product.
	ExpirationTime    *time.Time   `json:"expiration_time"`     // The expiry of your position.
	Side              *FuturesSide `json:"side"`                // The side of your position.
	NumberOfContracts *string      `json:"number_of_contracts"` // The size of your position in contracts.
	CurrentPrice      *string      `json:"current_price"`       // The current price of the product.
	AverageEntryPrice *string      `json:"avg_entry_price"`     // The average entry price at which you entered your current position.
	UnrealizedPNL     *string      `json:"unrealized_pnl"`      // Your current unrealized PnL for your position.
	DailyRealizedPNL  *string      `json:"daily_realized_pnl"`  // Your realized PnL from your trades in this product on current trade date.
}

type FuturesPositionSide

type FuturesPositionSide string
const (
	FuturesPositionSideUnspecified FuturesPositionSide = "FUTURES_POSITION_SIDE_UNSPECIFIED"
	FuturesPositionSideLong        FuturesPositionSide = "FUTURES_POSITION_SIDE_LONG"
	FuturesPositionSideShort       FuturesPositionSide = "FUTURES_POSITION_SIDE_SHORT"
)

type FuturesService

type FuturesService service

Interface for interacting with Fututres APIs.

Futures vs Spot Accounts

Futures and spot balances are held in different accounts. Cash is always deposited into your Coinbase Inc. (CBI) spot account. You can only acquire spot assets with funds in your spot account.

Treatment of Cash

Cash is automatically transferred to your Coinbase Financial Markets (CFM) futures account to satisfy margin requirements. Automatic transfers are only from CBI spot accounts to CFM futures accounts.
You can transfer cash that isn't being used to margin or maintain futures positions into your CBI spot account (to trade spot assets or to withdraw) with Schedule Futures Sweep.
Funds held in a CBI spot account do not receive the preferential treatment given to funds held in a regulated futures account, pursuant to CFTC's regulations and the U.S. Bankruptcy Code.

func (*FuturesService) CancelPendingSweep

func (s *FuturesService) CancelPendingSweep(ctx context.Context) (bool, error)

CancelPendingSweep cancels your pending sweep of funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet. Returns true if all sweeps are successfully canceled.

func (*FuturesService) GetBalanceSummary

func (s *FuturesService) GetBalanceSummary(ctx context.Context) (*BalanceSummary, error)

func (*FuturesService) GetPosition

func (s *FuturesService) GetPosition(ctx context.Context, id string) (*FuturesPosition, error)

GetPosition gets the position of a specific CFM futures product.

func (*FuturesService) ListPositions

func (s *FuturesService) ListPositions(ctx context.Context) ([]FuturesPosition, error)

ListPositions gets a list of all open positions in CFM futures products.

func (*FuturesService) ListSweeps

func (s *FuturesService) ListSweeps(ctx context.Context) ([]FuturesSweep, error)

ListSweeps gets information on your pending and/or processing requests to sweep funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.

  • A pending sweep is a sweep that has not started processing and can be cancelled.
  • A processing sweep is a sweep that is currently being processed and cannot be cancelled.

Once a sweep is complete, it longer appears in the list of sweeps

func (*FuturesService) ScheduleSweep

ScheduleSweep schedules a sweep of funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.

  • Sweep requests submitted before 5PM ET each day are processed the following business day.
  • Sweep requests submitted after 5PM ET each day are processed in 2 business days.

You can have at most one pending sweep request at a time.

Market movements related to your open positions may impact the final amount that is transferred into your spot account. The final funds transferred, up to your specified amount, depend on the available excess in your futures account.

type FuturesSide

type FuturesSide string
const (
	FuturesSideUnknown FuturesSide = "UNKNOWN"
	FuturesSideLong    FuturesSide = "LONG"
	FuturesSideShort   FuturesSide = "SHORT"
)

type FuturesSweep

type FuturesSweep struct {
	ID              *string `json:"id"` // The ID of the sweep request scheduled.
	RequestedAmount struct {
		Value    *string `json:"value"`
		Currency *string `json:"currency"`
	} `json:"requested_amount"` //The requested sweep amount.
	ShouldSweepAll *bool        `json:"should_sweep_all"` // True if the request was to sweep all available funds from your CFM futures account
	Status         *SweepStatus `json:"status"`           // A pending sweep is a sweep that has not started processing and can be cancelled. A processing sweep is a sweep that is currently being processed and cannot be cancelled.
	ScheduledTime  *time.Time   `json:"scheduled_time"`   // The timestamp at which the sweep request was submitted.
}

type GetBestBidAskResponse

type GetBestBidAskResponse struct {
	PriceBooks []PriceBook `json:"pricebooks"`
}

type GetMarketTradeOptions

type GetMarketTradeOptions struct {
	ProductID string     `url:"-"`                    // The trading pair, i.e., 'BTC-USD'.
	Limit     int        `url:"limit"`                // Number of trades to return.
	Start     *time.Time `url:"start,unix,omitempty"` // Timestamp for starting range of aggregations.
	End       *time.Time `url:"end,unix,omitempty"`   // Timestamp for starting range of aggregations.
}

type GetMarketTradesResponse

type GetMarketTradesResponse struct {
	Trades  []Trade `json:"trades"`
	BestBid *string `json:"best_bid"` // The best bid for the `product_id`, in quote currency.
	BestAsk *string `json:"best_ask"` // The best ask for the `product_id`, in quote currency.
}

type GetProductCandlesOptions

type GetProductCandlesOptions struct {
	ProductID   string          `url:"-"`           // The trading pair.
	Start       time.Time       `url:"start,unix"`  // Timestamp for starting range of aggregations.
	End         time.Time       `url:"end,unix"`    // Timestamp for ending range of aggregations.
	Granularity TimeGranularity `url:"granularity"` // The time slice value for each candle.
}

type GetTransactionsSummaryOptions

type GetTransactionsSummaryOptions struct {
	ProductType        *string             `url:"product_type,omitempty"`
	ContractExpiryType *ContractExpiryType `url:"contract_expiry_type,omitempty"`
}

type GetTransactionsSummaryResponse

type GetTransactionsSummaryResponse struct {
	TotalVolume         float64 `json:"total_volume"` // Total volume across assets, denoted in USD.
	TotalFees           float64 `json:"total_fees"`   // Total fees across assets, denoted in USD.
	FeeTier             FeeTier `json:"fee_tier"`
	GoodsAndServicesTax struct {
		Rate *string `json:"rate"`
		Type *string `json:"type"` // Possible values: [INCLUSIVE, EXCLUSIVE] // TODO: enum.
	} `json:"goods_and_services_tax"`
	AdvancedTradeOnlyVolume *float64 `json:"advanced_trade_only_volume"` // Advanced Trade volume (non-inclusive of Pro) across assets, denoted in USD.
	AdvancedTradeOnlyFees   *float64 `json:"advanced_trade_only_fees"`   // Advanced Trade fees (non-inclusive of Pro) across assets, denoted in USD.
	CoinbaseProVolume       *float64 `json:"coinbase_pro_volume"`        // Coinbase Pro volume across assets, denoted in USD.
	CoinbaseProFees         *float64 `json:"coinbase_pro_fees"`          // Coinbase Pro fees across assets, denoted in USD.
}

type Hold

type Hold struct {
	Value    string `json:"value"`    // Amount of currency that this object represents.
	Currency string `json:"currency"` // Denomination of the currency.
}

TODO: Not 100% sure what this is..?

type LimitOrderGTC

type LimitOrderGTC struct {
	BaseSize   *string `json:"base_size"`   // Amount of base currency to spend on order.
	LimitPrice *string `json:"limit_price"` // Ceiling price for which the order should get filled.
	PostOnly   *bool   `json:"post_only"`   // The post-only flag 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.
}

Limit Order Good Till Canceled. Limit orders are triggered based on the instructions around quantity and price: base_size represents the quantity of your base currency to spend; limit_price represents the maximum price at which the order should be filled. Good Till Canceled (gtc): orders remain open on the book until canceled.

type LimitOrderGTD

type LimitOrderGTD struct {
	BaseSize   *string    `json:"base_size"`   // Amount of base currency to spend on order.
	LimitPrice *string    `json:"limit_price"` // Ceiling price for which the order should get filled.
	EndTime    *time.Time `json:"end_time"`    // Time at which the order should be cancelled if it's not filled.
	PostOnly   *bool      `json:"post_only"`   // The post-only flag 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.
}

Limit Order Good Till Date. Limit orders are triggered based on the instructions around quantity and price: base_size represents the quantity of your base currency to spend; limit_price represents the maximum price at which the order should be filled. Good Till Date (gtd): orders are valid till a specified date or time.

type LiquidityIndicator

type LiquidityIndicator string
const (
	LiquidityIndicatorUnknown LiquidityIndicator = "UNKNOWN_LIQUIDITY_INDICATOR"
	LiquidityIndicatorMaker   LiquidityIndicator = "MAKER"
	LiquidityIndicatorTaker   LiquidityIndicator = "TAKER"
)

type ListAccountsResponse

type ListAccountsResponse struct {
	Accounts []Account `json:"accounts"`
	// Whether there are additional pages for this query.
	HasNext bool `json:"has_next"`
	// Cursor for paginating. Users can use this string to pass in the next call to this
	// endpoint, and repeat this process to fetch all accounts through pagination.
	Cursor *string `json:"cursor"`
	// Number of accounts returned
	Size *int32 `json:"size"`
}

type ListFillsResponse

type ListFillsResponse struct {
	Fills  []Fill  `json:"fills"`  // All fills matching the filters.
	Cursor *string `json:"cursor"` // Cursor for paginating. Users can use this string to pass in the next call to this endpoint, and repeat this process to fetch all fills through pagination.
}

type ListOrderFillsOptions

type ListOrderFillsOptions struct {
	OrderID           *string    `url:"order_id,omitempty"`                 // ID of order.
	ProductID         *string    `url:"product_id,omitempty"`               // The ID of the product this order was created for.
	StartSequenceTime *time.Time `url:"start_sequence_timestamp,omitempty"` // Start date. Only fills with a trade time at or after this start date are returned.
	EndSequenceTime   *time.Time `url:"end_sequence_timestamp,omitempty"`   // End date. Only fills with a trade time before this start date are returned.
	Limit             *int64     `url:"limit,omitempty"`                    // Maximum number of fills to return in response. Defaults to 100.
	Cursor            *string    `url:"cursor,omitempty"`                   // Cursor used for pagination. When provided, the response returns responses after this cursor.
}

type ListOrdersOptions

type ListOrdersOptions struct {
	ProductID            *string               `url:"product_id,omitempty"`             // Optional string of the product ID. Defaults to null, or fetch for all products.
	OrderStatus          []OrderStatus         `url:"order_status,omitempty"`           // A list of order statuses.
	Limit                *int32                `url:"limit,omitempty"`                  // Pagination limit with a default of 1000 (which is also the maximum). If has_next is true, additional orders are available to be fetched with pagination; also the cursor value in the response can be passed as cursor parameter in the subsequent request.
	StartDate            *time.Time            `url:"start_date,omitempty"`             // Start date to fetch orders from, inclusive.
	EndDate              *time.Time            `url:"end_date,omitempty"`               // An optional end date for the query window, exclusive. If provided only orders with creation time before this date will be returned.
	OrderType            *OrderType            `url:"order_type,omitempty"`             // Type of orders to return. Default is to return all order types.
	OrderSide            *OrderSide            `url:"order_side,omitempty"`             // Only orders matching this side are returned. Default is to return all sides.
	Cursor               *string               `url:"cursor,omitempty"`                 // Cursor used for pagination. When provided, the response returns responses after this cursor.
	ProductType          *ProductType          `url:"product_type,omitempty"`           // Only orders matching this product type are returned. Default is to return all product types.
	OrderPlacementSource *OrderPlacementSource `url:"order_placement_source,omitempty"` // Only orders matching this placement source are returned. Default is to return RETAIL_ADVANCED placement source.
	ContractExpiryType   *ContractExpiryType   `url:"contract_expiry_type,omitempty"`   // Only orders matching this contract expiry type are returned. Filter is only applied if product_type is set to FUTURE in the request.
	AssetFilters         []string              `url:"asset_filters,omitempty"`          // Only returns orders where the quote, base, or underlying asset matches the provided asset filter(s), i.e., 'BTC'.
	RetailPortfolioID    *string               `url:"retail_portfolio_id,omitempty"`    // Only orders matching this retail portfolio id are returned. Default is to return orders for all retail portfolio ids.
}

type ListOrdersResponse

type ListOrdersResponse struct {
	Orders   []Order `json:"orders"`   // A list of orders matching the query.
	Sequence *string `json:"sequence"` // The sequence of the db at which this state was read.
	HasNext  bool    `json:"has_next"` // Whether there are additional pages for this query.
	Cursor   *string `json:"cursor"`   // Cursor for paginating. Users can use this string to pass in the next call to this endpoint, and repeat this process to fetch all fills through pagination.
}

type ListPortfoliosOptions

type ListPortfoliosOptions struct {
	PortfolioType *PortfolioType `url:"portfolio_type,omitempty"`
}

type ListPortfoliosResponse

type ListPortfoliosResponse struct {
	Portfolios []Portfolio `json:"portfolios"`
}

type ListProductsOptions

type ListProductsOptions struct {
	Limit                  *int32                  `url:"limit,omitempty"`        // A limit describing how many products to return.
	Offset                 *int32                  `url:"limit,omitempty"`        // Number of products to offset before returning.
	ProductType            *ProductType            `url:"product_type,omitempty"` // Type of products to return.
	ProductIDs             []string                `url:"product_ids,omitempty"`  // List of product IDs to return.
	ContractExpiryType     *ContractExpiryType     `url:"contract_expiry_type,omitempty"`
	ExpiringContractStatus *ExpiringContractStatus `url:"expiring_contract_status,omitempty"`
}

type MarginType

type MarginType string
const (
	MarginTypeIsolated MarginType = "ISOLATED"
	MarginTypeCross    MarginType = "CROSS"
)

type MarketOrderIOC

type MarketOrderIOC struct {
	QuoteSize *string `json:"quote_size"` // Amount of quote currency to spend on order. Required for BUY orders
	BaseSize  *string `json:"base_size"`  // Amount of base currency to spend on order. Required for SELL orders.
}

Market Order Immediate Or Cancel. Market orders are used to BUY or SELL a desired product at the given market price. Immediate Or Cancel (ioc): orders instantly cancel the remaining size of the limit order instead of opening it on the book.

type Order

type Order struct {
	ID                    string                `json:"order_id"`            // The unique id for this order.
	ProductID             string                `json:"product_id"`          // The product this order was created for e.g. 'BTC-USD'.
	UserID                string                `json:"user_id"`             // The id of the User owning this Order.
	Configuration         *OrderConfiguration   `json:"order_configuration"` // Configuration of the order.
	Side                  *Side                 `json:"side"`                // Side the order is on (BUY, SELL).
	ClientOrderID         string                `json:"client_order_id"`     // Client specified ID of order.
	Status                *OrderStatus          `json:"status"`              // Status of the order.
	TimeInForce           *TimeInForce          `json:"time_in_force"`
	CreatedTime           time.Time             `json:"created_time"`            // Timestamp for when the order was created.
	CompletionPercentage  string                `json:"completion_percentage"`   // The percent of total order amount that has been filled.
	FilledSize            *string               `json:"filled_size"`             // The portion (in base currency) of total order amount that has been filled.
	AverageFilledPrice    string                `json:"average_filled_price"`    // The average of all prices of fills for this order.
	NumberOfFills         string                `json:"number_of_fills"`         // Number of fills that have been posted for this order.
	FilledValue           *string               `json:"filled_value"`            // The amount -- in quote currency -- of the total order that has been filled.
	PendingCancel         bool                  `json:"pending_cancel"`          // Whether a cancel request has been initiated for the order, and not yet completed.
	SizeInQuote           bool                  `json:"size_in_quote"`           // Whether the order was placed with quote currency.
	TotalFees             string                `json:"total_fees"`              // The total fees for the order.
	SizeInclusiveOfFees   bool                  `json:"size_inclusive_of_fees"`  // Whether the order size includes fees.
	TotalValueAfterFees   string                `json:"total_value_after_fees"`  // Derived field defined as (filled_value + total_fees) for buy orders and (filled_value - total_fees) for sell orders.
	TriggerStatus         *TriggerStatus        `json:"trigger_status"`          // Possible values: [UNKNOWN_TRIGGER_STATUS, INVALID_ORDER_TYPE, STOP_PENDING, STOP_TRIGGERED].
	Type                  *OrderType            `json:"order_type"`              // Possible values: [UNKNOWN_ORDER_TYPE, MARKET, LIMIT, STOP, STOP_LIMIT].
	RejectReason          *RejectReason         `json:"reject_reason"`           // Rejection Reason; Possible values: [REJECT_REASON_UNSPECIFIED].
	Settled               *bool                 `json:"settled"`                 // True if the order is fully filled, false otherwise.
	ProductType           *ProductType          `json:"product_type"`            // Possible values: [SPOT, FUTURE].
	RejectMessage         *string               `json:"reject_message"`          // Message stating why the order was rejected.
	CancelMessage         *string               `json:"cancel_message"`          // Message stating why the order was canceled.
	OrderPlacementSource  *OrderPlacementSource `json:"order_placement_source"`  // Possible values: [RETAIL_SIMPLE, RETAIL_ADVANCED].
	OutstandingHoldAmount *string               `json:"outstanding_hold_amount"` // The remaining hold amount calculated as (holdAmount - holdAmountReleased). If the hold is released, returns 0.
	IsLiquidation         *bool                 `json:"is_liquidation"`          // True if order is of liquidation type.
	LastFillTime          *time.Time            `json:"last_fill_time"`          // Time of the most recent fill for this order.
	EditHistory           []struct {
		Price                  *string    `json:"price"`
		Size                   *string    `json:"size"`
		ReplaceAcceptTimestamp *time.Time `json:"replace_accept_timestamp"`
	} `json:"edit_history"` // An array of the latest 5 edits per order.
}

type OrderConfiguration

type OrderConfiguration struct {
	MarketIOC    *MarketOrderIOC    `json:"market_market_ioc"`
	LimitGTC     *LimitOrderGTC     `json:"limit_limit_gtc"`
	LimitGTD     *LimitOrderGTD     `json:"limit_limit_gtd"`
	StopLimitGTC *StopLimitOrderGTC `json:"stop_limit_stop_limit_gtc"`
	StopLimitGTD *StopLimitOrderGTD `json:"stop_limit_stop_limit_gtd"`
}

Configuration of the order, it can only consist of a single order type at at time. The rest will not be populated.

type OrderFailureReason

type OrderFailureReason string
const (
	OrderFailureReasonUnknown                       OrderFailureReason = "UNKNOWN_FAILURE_REASON"
	OrderFailureReasonUnsupportedOrderConfiguration OrderFailureReason = "UNSUPPORTED_ORDER_CONFIGURATION"
	OrderFailureReasonInvalidSide                   OrderFailureReason = "INVALID_SIDE"
	OrderFailureReasonInvalidProductID              OrderFailureReason = "INVALID_PRODUCT_ID"
	OrderFailureReasonInvalidSizePrecision          OrderFailureReason = "INVALID_SIZE_PRECISION"
	OrderFailureReasonInvalidPricePrecision         OrderFailureReason = "INVALID_PRICE_PRECISION"
	OrderFailureReasonInsufficientFund              OrderFailureReason = "INSUFFICIENT_FUND"
	OrderFailureReasonInvalidLedgerBalance          OrderFailureReason = "INVALID_LEDGER_BALANCE"
	OrderFailureReasonOrderEntryDisabled            OrderFailureReason = "ORDER_ENTRY_DISABLED"
	OrderFailureReasonIneligiblePair                OrderFailureReason = "INELIGIBLE_PAIR"
	OrderFailureReasonInvalidLimitPricePostOnly     OrderFailureReason = "INVALID_LIMIT_PRICE_POST_ONLY"
	OrderFailureReasonInvalidLimitPrice             OrderFailureReason = "INVALID_LIMIT_PRICE"
	OrderFailureReasonInvalidNoLiquidity            OrderFailureReason = "INVALID_NO_LIQUIDITY"
	OrderFailureReasonInvalidRequest                OrderFailureReason = "INVALID_REQUEST"
	OrderFailureReasonCommanderRejectedNewOrder     OrderFailureReason = "COMMANDER_REJECTED_NEW_ORDER"
	OrderFailureReasonInsufficientFunds             OrderFailureReason = "INSUFFICIENT_FUNDS"
)

type OrderPlacementSource

type OrderPlacementSource string
const (
	OrderPlacementSourceRetailSimple   OrderPlacementSource = "RETAIL_SIMPLE"
	OrderPlacementSourceRetailAdvanced OrderPlacementSource = "RETAIL_ADVANCED"
)

type OrderSide

type OrderSide string
const (
	OrderSideUnknown OrderSide = "UNKNOWN_ORDER_SIDE"
	OrderSideBuy     OrderSide = "BUY"
	OrderSideSell    OrderSide = "SELL"
)

type OrderStatus

type OrderStatus string
const (
	OrderStatusOpen      OrderStatus = "OPEN"
	OrderStatusFilled    OrderStatus = "FILLED"
	OrderStatusCancelled OrderStatus = "CANCELLED"
	OrderStatusExpired   OrderStatus = "EXPIRED"
	OrderStatusUnknown   OrderStatus = "UNKNOWN_ORDER_STATUS"
)

type OrderType

type OrderType string
const (
	OrderTypeUnknown   OrderType = "UNKNOWN_ORDER_TYPE"
	OrderTypeMarket    OrderType = "MARKET"
	OrderTypeLimt      OrderType = "LIMIT"
	OrderTypeStop      OrderType = "STOP"
	OrderTypeStopLimit OrderType = "STOP_LIMIT"
)

type OrdersService

type OrdersService service

func (*OrdersService) Cancel

func (s *OrdersService) Cancel(ctx context.Context, ids ...string) ([]CancelledOrder, error)

Cancel initiates cancel requests for one or more orders.

The maximum number of order_ids that can be cancelled per request is 100. This number may be subject to change in emergency, but if a request exceeds the max, then an InvalidArgument error code will be returned with an error message denoting the limit Too many orderIDs entered, limit is _.

func (*OrdersService) Create

func (s *OrdersService) Create(ctx context.Context, options CreateOrderOptions) (any, error)

func (*OrdersService) Edit

Edit an order with a specified new size, or new price. Only limit order types, with time in force type of good-till-cancelled can be edited.

Order Priority:

  • A client can only send an Edit Order request after the previous request for the same order has been fully processed.
  • CAUTION: You lose your place in line if you increase size or increase/decrease price.

func (*OrdersService) EditPreview

func (s *OrdersService) EditPreview(ctx context.Context, options EditOrderOptions) (*EditOrderResponse, error)

EditPreview simulates an edit order request with a specified new size, or new price, to preview the result of an edit. Only limit order types, with time in force type of good-till-cancelled can be edited

func (*OrdersService) Get

func (s *OrdersService) Get(ctx context.Context, id string) (*Order, error)

Get retrieves a single order by order ID.

func (*OrdersService) List

List gets a list of orders filtered by optional query parameters (product_id, order_status, etc).

  1. The maximum number of OPEN orders returned is 1000. If you have more than 1000 open, its recommended to use the WebSocket User channel to retrieve all OPEN orders.

  2. start_date and end_date parameters don’t apply to open orders.

    You cannot query for OPEN orders with other order types. # Allowed /orders/historical/batch?order_status=OPEN /orders/historical/batch?order_status=CANCELLED,EXPIRED

    # Not allowed /orders/historical/batch?order_status=OPEN,CANCELLED

func (*OrdersService) ListFills

Get a list of fills filtered by optional query parameters (product_id, order_id, etc).

type PorfoliosMoveFundsResponse

type PorfoliosMoveFundsResponse struct {
	SourcePortfolioUUID *uuid.UUID `json:"source_portfolio_uuid"` // UUID of the portfolio the funds were transfered from.
	TargetPortfolioUUID *uuid.UUID `json:"target_portfolio_uuid"` // UUID of the portfolio the funds were transfered to.
}

type Portfolio

type Portfolio struct {
	Name    *string        `json:"name"`
	UUID    *uuid.UUID     `json:"uuid"`
	Type    *PortfolioType `json:"type"`
	Deleted *bool          `json:"deleted"`
}

type PortfolioMoveFundsOptions

type PortfolioMoveFundsOptions struct {
	Funds               Funds     `json:"funds"`                 // Represents a monetary amount.
	SourcePortfolioUUID uuid.UUID `json:"source_portfolio_uuid"` // UUID of the portfolio to transfer funds from.
	TargetPortfolioUUID uuid.UUID `json:"target_portfolio_uuid"` // UUID of the portfolio to transfer funds to.
}

type PortfolioType

type PortfolioType string
const (
	PortfolioTypeUndefined PortfolioType = "UNDEFINED"
	PortfolioTypeDefault   PortfolioType = "DEFAULT"
	PortfolioTypeConsumer  PortfolioType = "CONSUMER"
	PortfolioTypeINTX      PortfolioType = "INTX"
)

type PortfoliosService

type PortfoliosService service

func (*PortfoliosService) Allocate

Allocate allocates more funds to an isolated position in your Perpetuals portfolio.

func (*PortfoliosService) Create

func (s *PortfoliosService) Create(ctx context.Context, name string) (*Portfolio, error)

Create creates a portfolio.

func (*PortfoliosService) Delete

func (s *PortfoliosService) Delete(ctx context.Context, id uuid.UUID) error

Delete deletes a portfolio by portfolio ID.

func (*PortfoliosService) Edit

Edit modifies a portfolio by portfolio ID.

func (*PortfoliosService) List

List gets a list of all portfolios of a user.

func (*PortfoliosService) MoveFunds

MoveFunds transfers funds between portfolios.

type PreviewFailureReason

type PreviewFailureReason string
const (
	PreviewFailureReasonUnknown                        PreviewFailureReason = "UNKNOWN_PREVIEW_FAILURE_REASON"
	PreviewFailureReasonMissingCommissionRate          PreviewFailureReason = "PREVIEW_MISSING_COMMISSION_RATE"
	PreviewFailureReasonInvalidSide                    PreviewFailureReason = "PREVIEW_INVALID_SIDE"
	PreviewFailureReasonInvalidOrderConfig             PreviewFailureReason = "PREVIEW_INVALID_ORDER_CONFIG"
	PreviewFailureReasonInvalidProductID               PreviewFailureReason = "PREVIEW_INVALID_PRODUCT_ID"
	PreviewFailureReasonInvalidSizePrecision           PreviewFailureReason = "PREVIEW_INVALID_SIZE_PRECISION"
	PreviewFailureReasonInvalidPricePrecision          PreviewFailureReason = "PREVIEW_INVALID_PRICE_PRECISION"
	PreviewFailureReasonMissingProductPriceBook        PreviewFailureReason = "PREVIEW_MISSING_PRODUCT_PRICE_BOOK"
	PreviewFailureReasonInvalidLedgerBalance           PreviewFailureReason = "PREVIEW_INVALID_LEDGER_BALANCE"
	PreviewFailureReasonInsufficientLedgerBalance      PreviewFailureReason = "PREVIEW_INSUFFICIENT_LEDGER_BALANCE"
	PreviewFailureReasonInvalidLimitPricePostOnly      PreviewFailureReason = "PREVIEW_INVALID_LIMIT_PRICE_POST_ONLY"
	PreviewFailureReasonInvalidLimitPrice              PreviewFailureReason = "PREVIEW_INVALID_LIMIT_PRICE"
	PreviewFailureReasonInvalidNoLiquidity             PreviewFailureReason = "PREVIEW_INVALID_NO_LIQUIDITY"
	PreviewFailureReasonInsufficientFund               PreviewFailureReason = "PREVIEW_INSUFFICIENT_FUND"
	PreviewFailureReasonInvalidCommissionConfiguration PreviewFailureReason = "PREVIEW_INVALID_COMMISSION_CONFIGURATION"
	PreviewFailureReasonInvalidStopPrice               PreviewFailureReason = "PREVIEW_INVALID_STOP_PRICE"
	PreviewFailureReasonInvalidBaseSizeTooLarge        PreviewFailureReason = "PREVIEW_INVALID_BASE_SIZE_TOO_LARGE"
	PreviewFailureReasonInvalidBaseSizeTooSmall        PreviewFailureReason = "PREVIEW_INVALID_BASE_SIZE_TOO_SMALL"
	PreviewFailureReasonInvalidQuoteSizePrecision      PreviewFailureReason = "PREVIEW_INVALID_QUOTE_SIZE_PRECISION"
	PreviewFailureReasonInvalidQuoteSizeTooLarge       PreviewFailureReason = "PREVIEW_INVALID_QUOTE_SIZE_TOO_LARGE"
	PreviewFailureReasonInvalidPriceTooLarge           PreviewFailureReason = "PREVIEW_INVALID_PRICE_TOO_LARGE"
	PreviewFailureReasonInvalidQuoteSizeTooSmall       PreviewFailureReason = "PREVIEW_INVALID_QUOTE_SIZE_TOO_SMALL"
	PreviewFailureReasonInsufficientFundsForFutures    PreviewFailureReason = "PREVIEW_INSUFFICIENT_FUNDS_FOR_FUTURES"
	PreviewFailureReasonBreachedPriceLimit             PreviewFailureReason = "PREVIEW_BREACHED_PRICE_LIMIT"
	PreviewFailureReasonBreachedAccountPositionLimit   PreviewFailureReason = "PREVIEW_BREACHED_ACCOUNT_POSITION_LIMIT"
	PreviewFailureReasonBreachedCompanyPositionLimit   PreviewFailureReason = "PREVIEW_BREACHED_COMPANY_POSITION_LIMIT"
	PreviewFailureReasonInvalidMarginHealth            PreviewFailureReason = "PREVIEW_INVALID_MARGIN_HEALTH"
	PreviewFailureReasonRiskProxyFailure               PreviewFailureReason = "PREVIEW_RISK_PROXY_FAILURE"
	PreviewFailureReasonUntradableFCMAccountStatus     PreviewFailureReason = "PREVIEW_UNTRADABLE_FCM_ACCOUNT_STATUS"
)

type PriceBook

type PriceBook struct {
	ProductID string     `json:"product_id"`
	Bids      []BidAsk   `json:"bids"`
	Asks      []BidAsk   `json:"asks"`
	Time      *time.Time `json:"time"`
}

type Product

type Product struct {
	ID                            string                    `json:"product_id"`                   // The trading pair.
	Price                         string                    `json:"price"`                        // The current price for the product, in quote currency.
	PricePercentageChange24Hours  string                    `json:"price_percentage_change_24h"`  // The amount the price of the product has changed, in percent, in the last 24 hours.
	Volume24Hours                 string                    `json:"volume_24h"`                   // The trading volume for the product in the last 24 hours.
	VolumePercentageChange24Hours string                    `json:"volume_percentage_change_24h"` // The percentage amount the volume of the product has changed in the last 24 hours.
	BaseIncrement                 string                    `json:"base_increment"`               // Minimum amount base value can be increased or decreased at once.
	QuoteIncrement                string                    `json:"quote_increment"`              // Minimum amount quote value can be increased or decreased at once.
	QuoteMinimumSize              string                    `json:"quote_min_size"`               // Minimum size that can be represented of quote currency.
	QuoteMaximumSize              string                    `json:"quote_max_size"`               // Maximum size that can be represented of quote currency.
	BaseMinimimSize               string                    `json:"base_min_size"`                // Minimum size that can be represented of base currency.
	BaseMaximumSize               string                    `json:"base_max_size"`                // Maximum size that can be represented of base currency.
	BaseName                      string                    `json:"base_name"`                    // Name of the base currency.
	QuoteName                     string                    `json:"quote_name"`                   // Name of the quote currency.
	Watched                       bool                      `json:"watched"`                      // Whether or not the product is on the user's watchlist.
	IsDisabled                    bool                      `json:"is_disabled"`                  // Whether or not the product is disabled for trading.
	New                           bool                      `json:"new"`                          // Whether or not the product is 'new'.
	Status                        string                    `json:"status"`                       // Status of the product.
	CancelOnly                    bool                      `json:"cancel_only"`                  // Whether or not orders of the product can only be cancelled, not placed or edited.
	LimitOnly                     bool                      `json:"limit_only"`                   // Whether or not orders of the product can only be limit orders, not market orders.
	PostOnly                      bool                      `json:"post_only"`                    // Whether or not orders of the product can only be posted, not cancelled.
	TradingDisabled               bool                      `json:"trading_disabled"`             // Whether or not the product is disabled for trading for all market participants.
	AuctionMode                   bool                      `json:"auction_mode"`                 // Whether or not the product is in auction mode.
	Type                          *ProductType              `json:"product_type"`                 // Type of product.
	QuoteCurrencyID               *string                   `json:"quote_currency_id"`            // Symbol of the quote currency.
	BaseCurrencyID                *string                   `json:"base_currency_id"`             // Symbol of the base currency.
	FCMTradingSessionDetails      *FCMTradingSessionDetails `json:"fcm_trading_session_details"`
	MidMarketPrice                *string                   `json:"mid_market_price"`     // The current midpoint of the bid-ask spread, in quote currency.
	Alias                         *string                   `json:"alias"`                // Product id for the corresponding unified book.
	AliasTo                       []string                  `json:"alias_to"`             // Product ids that this product serves as an alias for.
	BaseDisplaySymbol             string                    `json:"base_display_symbol"`  // Symbol of the base display currency.
	QuoteDisplaySymbol            string                    `json:"quote_display_symbol"` // Symbol of the quote display currency.
	ViewOnly                      *bool                     `json:"view_only"`            // Whether or not the product is in view only mode.
	PriceIncrement                *string                   `json:"price_increment"`      // Minimum amount price can be increased or decreased at once.
	FutureProductDetails          *FutureProductDetails     `json:"future_product_details"`
}

type ProductType

type ProductType string
const (
	ProductTypeSpot ProductType = "SPOT"
	Future          ProductType = "FUTURE"
)

type ProductsService

type ProductsService service

func (*ProductsService) Get

func (s *ProductsService) Get(ctx context.Context, id string) (*Product, error)

Get gets information on a single product by product ID.

func (*ProductsService) GetBestBidAsk

func (s *ProductsService) GetBestBidAsk(ctx context.Context, ids ...string) (*GetBestBidAskResponse, error)

GetBestBidAsk gets the best bid/ask for all products. A subset of all products can be returned instead by using the product_ids input.

func (*ProductsService) GetMarketTrades

Get snapshot information, by product ID, about the last trades (ticks), best bid/ask, and 24h volume.

func (*ProductsService) GetProductBook

func (s *ProductsService) GetProductBook(ctx context.Context, id string, limit *int) (*PriceBook, error)

GetProductBook gets a list of bids/asks for a single product. The amount of detail shown can be customized with the limit parameter.

func (*ProductsService) GetProductCandles

func (s *ProductsService) GetProductCandles(ctx context.Context, options GetProductCandlesOptions) ([]Candles, error)

GetProductCandles gets rates for a single product by product ID, grouped in buckets. id: The trading pair. start: Timestamp for starting range of aggregations. end: Timestamp for ending range of aggregations. granularity: The time slice value for each candle.

func (*ProductsService) List

func (s *ProductsService) List(ctx context.Context, options *ListProductsOptions) ([]Product, error)

type RejectReason

type RejectReason string
const (
	RejectReasonUnknown RejectReason = "REJECT_REASON_UNSPECIFIED"
)

type RiskManagedBy

type RiskManagedBy string
const (
	RiskManagedByUnknown RiskManagedBy = "UNKNOWN_RISK_MANAGEMENT_TYPE"
	RiskManagedByFCM     RiskManagedBy = "MANAGED_BY_FCM"
	RiskManagedByVenue   RiskManagedBy = "MANAGED_BY_VENUE"
)

type ScheduleSweepOptions

type ScheduleSweepOptions struct {
	USDAmmount *string `json:"usd_amount"` // The amount you want to sweep from your CFM futures account into your CBI spot account. Leave empty to sweep all available excess funds.
}

type ScheduleSweepResponse

type ScheduleSweepResponse struct {
	Success *bool `json:"success"`
}

type Side

type Side string
const (
	SideBuy  Side = "BUY"
	SideSell Side = "SELL"
)

type StopDirection

type StopDirection string
const (
	StopDirectionUp   StopDirection = "STOP_DIRECTION_STOP_UP"
	StopDirectionDown StopDirection = "STOP_DIRECTION_STOP_DOWN"
)

type StopLimitOrderGTC

type StopLimitOrderGTC struct {
	BaseSize      *string        `json:"base_size"`      // Amount of base currency to spend on order.
	LimitPrice    *string        `json:"limit_price"`    // Ceiling price for which the order should get filled.
	StopPrice     *string        `json:"stop_price"`     // Price at which the order should trigger - if stop direction is Up, then the order will trigger when the last trade price goes above this, otherwise order will trigger when last trade price goes below this price.
	StopDirection *StopDirection `json:"stop_direction"` // Possible values: [STOP_DIRECTION_STOP_UP, STOP_DIRECTION_STOP_DOWN].
}

Stop Order Good Till Canceled. Stop orders are triggered based on the movement of the last trade price. The last trade price is the last price at which an order was filled. Good Till Canceled (gtc): orders remain open on the book until canceled.

type StopLimitOrderGTD

type StopLimitOrderGTD struct {
	BaseSize      *string    `json:"base_size"`      // Amount of base currency to spend on order.
	LimitPrice    *string    `json:"limit_price"`    // Ceiling price for which the order should get filled.
	StopPrice     *string    `json:"stop_price"`     // Price at which the order should trigger - if stop direction is Up, then the order will trigger when the last trade price goes above this, otherwise order will trigger when last trade price goes below this price.
	EndTime       *time.Time `json:"end_time"`       // Time at which the order should be cancelled if it's not filled.
	StopDirection *string    `json:"stop_direction"` // Possible values: [STOP_DIRECTION_STOP_UP, STOP_DIRECTION_STOP_DOWN].
}

Stop Order Good Till Date. Stop orders are triggered based on the movement of the last trade price. The last trade price is the last price at which an order was filled. Good Till Date (gtd): orders are valid till a specified date or time.

type SweepStatus

type SweepStatus string
const (
	SweepStatusUnknown    SweepStatus = "UNKNOWN_FCM_SWEEP_STATUS"
	SweepStatusPending    SweepStatus = "PENDING"
	SweepStatusProcessing SweepStatus = "PROCESSING"
)

type TimeGranularity

type TimeGranularity string
const (
	TimeGranularityUnknown        TimeGranularity = "UNKNOWN_GRANULARITY"
	TimeGranularityOneMinute      TimeGranularity = "ONE_MINUTE"
	TimeGranularityFiveMinutes    TimeGranularity = "FIVE_MINUTE"
	TimeGranularityFifteenMinutes TimeGranularity = "FIFTEEN_MINUTE"
	TimeGranularityThirtyMinutes  TimeGranularity = "THIRTY_MINUTE"
	TimeGranularityOneHour        TimeGranularity = "ONE_HOUR"
	TimeGranularityTwoHours       TimeGranularity = "TWO_HOUR"
	TimeGranularitySixHours       TimeGranularity = "SIX_HOUR"
	TimeGranularityOneDay         TimeGranularity = "ONE_DAY"
)

type TimeInForce

type TimeInForce string
const (
	TimeInForceUnknown            TimeInForce = "UNKNOWN_TIME_IN_FORCE" // Unknown or unspecified.
	TimeInForceGoodUntilDate      TimeInForce = "GOOD_UNTIL_DATE_TIME"  // Orders are valid till a specified date or time.
	TimeInForceGoodUntilCancelled TimeInForce = "GOOD_UNTIL_CANCELLED"  //  orders remain open on the book until canceled.
	TimeInForceImmediateOrCancel  TimeInForce = "IMMEDIATE_OR_CANCEL"   // orders instantly cancel the remaining size of the limit order instead of opening it on the book.
)

type Trade

type Trade struct {
	ID        *string    `json:"trade_id"`   // The ID of the trade that was placed.
	ProductID *string    `json:"product_id"` // The trading pair.
	Price     *string    `json:"price"`      // The price of the trade, in quote currency.
	Size      *string    `json:"size"`       // The size of the trade, in base currency.
	Time      *time.Time `json:"time"`       // The time of the trade.
	Side      *Side      `json:"side"`       // Side of the transaction the trade is on: [BUY, SELL].
	Bid       *string    `json:"bid"`        // The best bid for the `product_id`, in quote currency.
	Ask       *string    `json:"ask"`        // The best ask for the `product_id`, in quote currency.
}

type TradeType

type TradeType string
const (
	TradeTypeFill       TradeType = "FILL"
	TradeTypeReversal   TradeType = "REVERSAL"
	TradeTypeCorrection TradeType = "CORRECTION"
	TradeTypeSynthetic  TradeType = "SYNTHETIC"
)

type TriggerStatus

type TriggerStatus string
const (
	TriggerStatusUnknown          TriggerStatus = "UNKNOWN_TRIGGER_STATUS"
	TriggerStatusInvalidOrderType TriggerStatus = "INVALID_ORDER_TYPE"
	TriggerStatusStopPending      TriggerStatus = "STOP_PENDING"
	TriggerStatusStopTriggered    TriggerStatus = "STOP_TRIGGERED"
)

Jump to

Keyboard shortcuts

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