coinbasev3

package module
v0.0.0-...-7b3a89e Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2023 License: MIT Imports: 15 Imported by: 0

README

Coinbase Advanced Trades API (v3) Tests Status GoDoc

This is a Go client for the Coinbase Advanced Trades API (v3). Work in progress.

Note: The advanced trading API does not have a sandbox available at this time. All tests have been mocked to ensure the client works as expected. Once the sandbox is available for the advanced trading API the tests will be updated to use the sandbox.

Installation

go get github.com/cloudmanic/go-coinbasev3

Progress

Resource: Rest API Pro Mapping

  • Websocket Feed Advanced Trade WebSocket Docs
  • Public API (No authentication needed)
  • Advanced Trade API (V3) Advanced Trade REST API Docs
    • List Accounts
    • Get Account
    • Create Order
    • Cancel Orders
    • Edit Order
    • Edit Order Preview
    • List Orders
    • List Fills
    • Get Order
    • Get Best Bid/Ask
    • Get Product Book
    • List Products
    • Get Product
    • Get Product Candles
    • Get Market Trades
    • Get Transactions Summary
  • Sign In with Coinbase API v2
    • Show an Account
    • List Transactions
    • Show Address
    • Create Address
    • Get Currencies
    • Deposit funds
    • List Payment Methods
    • List Transactions
    • Show a Transaction
    • Send Money
    • Withdraw Funds

HTTP Client Usage

// the client will automatically sign requests with the api_key and secret_key using req's OnBeforeRequest callback
client := coinbasev3.NewApiClient("api_key", "secret_key")

// product is a struct defined in the coinbasev3 package
product, err := client.GetProduct(productId)
if err != nil {
    panic("Failed to get product")
}
Error Handling

The client will return an error if the response status code is not 200, the retries run out of attempts, or the []byte response can't properly marshal the result into json.

There is an error wrapper coinbasev3.ResponseError that will contain the error message and a marshaled coinbase error struct.

For most cases, the normal error message should contain enough information to determine what went wrong. However, if you need to access the coinbase error struct you can use the errors.As function to check if the error is a coinbasev3.ResponseError and then access the CoinbaseError field.

res, err := client.EditOrder(coinbasev3.EditOrderRequest{
    OrderId: "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
    Size:    "1.00",
    Price:   "0.01",	
})
if err != nil {
    var myErr coinbasev3.ResponseError
    if errors.As(err, &myErr) {
        panic(err.(coinbasev3.ResponseError).CoinbaseError)
    } else {
        panic("Failed to edit order")
    }
}
Changing base URL

The advanced trading API does not currently have a sandbox available. The sandbox is only available for the Coinbase API v2. The base URL can be changed to the sandbox URL for the Coinbase API v2 endpoints. Will need to revisit this once the sandbox is available for the advanced trading API.

client := coinbasev3.NewApiClient("api_key", "secret_key")
client.SetBaseUrlV3("https://api-public.sandbox.pro.coinbase.com")
client.SetBaseUrlV2("https://api-public.sandbox.coinbase.com")
client.SetBaseExchangeUrl("https://api.exchange.coinbase.com")

Websocket

The websocket client is a wrapper around the gorilla websocket with a few extra features to make it easier to use with the Coinbase Advanced Trade API. The socket will automatically handle reconnections in the background to ensure you can run your sockets for long periods of time without worrying about the connection dropping. This is the reason why the configuration requires the channel subscriptions prior to initializing the client. In order for the connection to reconnect properly it will need to re-subscribe to the channels that were previously subscribed to.

// create a list of products to subscribe to 
// follows best practices mentioned in docs: https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-best-practices)
products := []string{"ETH-USD", "BTC-USD"}
// use one read channel for all products
readCh := make(chan []byte)
for _, product := range products {
  // create a ticker + heartbeat channel subscription. See: https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels
  wsChannels := []coinbasev3.WebsocketChannel{
    coinbasev3.NewTickerChannel([]string{product}),
    coinbasev3.NewHeartbeatsChannel([]string{product}),
  }
  
  // create a minimal websocket config
  wsConfig := coinbasev3.NewWsConfig("api_key", "secret_key", readCh, wsChannels)
  
  // create a websocket client with the config
  ws, err := coinbasev3.NewWsClient(wsConfig)
  if err != nil {
  panic("Failed to create Coinbase websocket client")
  }
  
  // open the websocket connection
  _, err = ws.Connect()
  if err != nil {
  panic("Failed to connect to Coinbase websocket")
  }
}

// read messages from the websocket
for {
    select {
        case msg := <-readCh:
            log.Println(string(msg))
    }
}

// will close the connection and stop the reconnection loop
ws.Shutdown()
Reading messages from the websocket

The decision to use a read channel (instead of a callback) is to allow a more flexible dx, while also allowing the underlying socket to re-connect without any external interruptions or maintenance. The read channel will remain open for the entirety of the scope of the websocket client. If the websocket client is shutdown the read channel will be closed as well.

Note on the read channel data type

The read channel uses []byte instead of a default struct because the websocket client does not know what type of message it is receiving. The websocket client will not attempt to parse the message in any way. It is up to the developer to parse the message into the appropriate struct.

Parsing into pre-defined structs

For ease of use there are some helper functions to parse the messages into the appropriate struct. These helpers are not required to use the websocket client.

To utilize the helper functions you can parse the message into the default event struct, which is coinbasev3.Event.

Once you have the event struct you can use the evt.IsTickerEvent(), evt.IsHeartbeatEvent(), etc... to determine what type of event it is. Then you can use the evt.GetTickerEvent(), evt.GetHeartbeatEvent(), etc... to convert the default event into the appropriate struct.

var evt coinbasev3.Event // default event struct (the events array is defined as an interface{})
err := json.Unmarshal(msg, &evt)
if err != nil {
  panic(err)
}

// check if the event is a ticker event
if evt.IsTickerEvent() {
  // convert the event into a ticker event struct
  tick, err := evt.GetTickerEvent()
  if err != nil {
      panic(err)
  }
}

Run tests

go test ./... -v

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidReadChannel = fmt.Errorf("read channel is invalid")
	ErrNoApiKey           = fmt.Errorf("no api key provided")
	ErrNoSecretKey        = fmt.Errorf("no secret key provided")
	ErrNotConnected       = fmt.Errorf("not connected")
)
View Source
var (
	ErrFailedToUnmarshal = fmt.Errorf("failed to unmarshal response")
)

Functions

func SignHmacSha256

func SignHmacSha256(str, secret string) []byte

Types

type Account

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

type AccountAvailableBalance

type AccountAvailableBalance struct {
	Value    string `json:"value"`
	Currency string `json:"currency"`
}

type AccountHold

type AccountHold struct {
	Value    string `json:"value"`
	Currency string `json:"currency"`
}

type ApiClient

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

func NewApiClient

func NewApiClient(apiKey, secretKey string, clients ...HttpClient) *ApiClient

NewApiClient creates a new Coinbase API client. The API key and secret key are used to sign requests. The default timeout is 10 seconds. The default retry count is 3. The default retry backoff interval is 1 second to 5 seconds.

func (*ApiClient) CancelOrders

func (c *ApiClient) CancelOrders(orderIds []string) (CancelOrdersData, error)

CancelOrders initiate cancel requests for one or more orders.

func (*ApiClient) CreateOrder

func (c *ApiClient) CreateOrder(req CreateOrderRequest) (CreateOrderData, error)

CreateOrder create an order with a specified product_id (asset-pair), side (buy/sell), etc.

func (*ApiClient) EditOrder

func (c *ApiClient) EditOrder(req EditOrderRequest) (EditOrderData, error)

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

func (*ApiClient) EditOrderPreview

func (c *ApiClient) EditOrderPreview(req EditOrderRequest) (EditOrderPreviewData, error)

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

func (*ApiClient) GetAccount

func (c *ApiClient) GetAccount(uuid string) (Account, error)

GetAccount get a list of information about an account, given an account UUID.

func (*ApiClient) GetBestBidAsk

func (c *ApiClient) GetBestBidAsk(productIds []string) (BestBidAskData, error)

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

func (*ApiClient) GetBuyPrice

func (c *ApiClient) GetBuyPrice(pair string) (CurrencyPairPrice, error)

GetBuyPrice get the total price to buy a currency.

func (*ApiClient) GetCurrencies

func (c *ApiClient) GetCurrencies() (Currencies, error)

GetCurrencies lists known cryptocurrencies.

func (*ApiClient) GetExchangeRates

func (c *ApiClient) GetExchangeRates(currency string) (ExchangeRates, error)

GetExchangeRates get current exchange rates. Default base currency is USD, but it can be defined as any supported currency

func (*ApiClient) GetFiatCurrencies

func (c *ApiClient) GetFiatCurrencies() (FiatCurrencies, error)

GetFiatCurrencies lists known fiat currencies. Currency codes conform to the ISO 4217 standard where possible

func (*ApiClient) GetListFills

func (c *ApiClient) GetListFills(q ListFillsQuery) (ListFillsData, error)

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

func (*ApiClient) GetListOrders

func (c *ApiClient) GetListOrders(q ListOrdersQuery) (ListOrdersData, error)

GetListOrders get a list of orders filtered by optional query parameters (product_id, order_status, etc). Note: You cannot pair open orders with other order types. Example: order_status=OPEN,CANCELLED will return an error.

func (*ApiClient) GetMarketTrades

func (c *ApiClient) GetMarketTrades(productId string, limit int32) (MarketTradesData, error)

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

func (*ApiClient) GetOrder

func (c *ApiClient) GetOrder(orderId string) (Order, error)

GetOrder get a single order by order ID.

func (*ApiClient) GetProduct

func (c *ApiClient) GetProduct(productId string) (Product, error)

GetProduct get information on a single product by product ID.

func (*ApiClient) GetProductBook

func (c *ApiClient) GetProductBook(productId string, limit int32) (ProductBookData, error)

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

func (*ApiClient) GetProductCandles

func (c *ApiClient) GetProductCandles(productId, start, end string, granularity Granularity) ([]ProductCandles, error)

GetProductCandles get rates for a single product by product ID, grouped in buckets.

func (*ApiClient) GetProducts

func (c *ApiClient) GetProducts() ([]Products, error)

GetProducts gets a list of available currency pairs for trading.

func (*ApiClient) GetSellPrice

func (c *ApiClient) GetSellPrice(pair string) (CurrencyPairPrice, error)

GetSellPrice get the total price to sell a currency.

func (*ApiClient) GetServerTime

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

GetServerTime get the API server time.

func (*ApiClient) GetSpotPrice

func (c *ApiClient) GetSpotPrice(pair string) (CurrencyPairPrice, error)

GetSpotPrice get the current market price of a currency.

func (*ApiClient) GetTransactionSummary

func (c *ApiClient) GetTransactionSummary(req TransactionSummaryRequest) (TransactionSummaryData, error)

GetTransactionSummary get a summary of transactions with fee tiers, total volume, and fees.

func (*ApiClient) ListAccounts

func (c *ApiClient) ListAccounts(limit int, cursor string) (ListAccountsData, error)

ListAccounts gets a list of authenticated accounts for the current user.

func (*ApiClient) SetBaseExchangeUrl

func (c *ApiClient) SetBaseExchangeUrl(url string)

SetBaseExchangeUrl sets the base URL for the Coinbase Exchange API.

func (*ApiClient) SetBaseUrlV2

func (c *ApiClient) SetBaseUrlV2(url string)

SetBaseUrlV2 sets the base URL for the Sign In With Coinbase APIs.

func (*ApiClient) SetBaseUrlV3

func (c *ApiClient) SetBaseUrlV3(url string)

SetBaseUrlV3 sets the base URL for the Coinbase Advanced Trading API.

func (*ApiClient) SetSandboxUrls

func (c *ApiClient) SetSandboxUrls()

SetSandboxUrls sets the base URLs to the sandbox environment. Note: The sandbox for Advanced Trading is not yet available. This method will be revisited when the sandbox is available.

type BestBidAskData

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

type CancelOrderResult

type CancelOrderResult struct {
	Success       bool   `json:"success"`
	FailureReason string `json:"failure_reason"`
	OrderId       string `json:"order_id"`
}

type CancelOrderResults

type CancelOrderResults []CancelOrderResult

func (*CancelOrderResults) UnmarshalJSON

func (o *CancelOrderResults) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. Required because Coinbase returns an array of orders or a single order object.

type CancelOrdersData

type CancelOrdersData struct {
	Results CancelOrderResults `json:"results"`
}

type Candle

type Candle struct {
	Start     string `json:"start" mapstructure:"start"`
	High      string `json:"high" mapstructure:"high"`
	Low       string `json:"low" mapstructure:"low"`
	Open      string `json:"open" mapstructure:"open"`
	Close     string `json:"close" mapstructure:"close"`
	Volume    string `json:"volume" mapstructure:"volume"`
	ProductId string `json:"product_id" mapstructure:"product_id"`
}

type CandlesEvent

type CandlesEvent struct {
	Event
	Events []CandlesEventType `json:"events"`
}

type CandlesEventType

type CandlesEventType struct {
	Type    string   `json:"type"`
	Candles []Candle `json:"candles"`
}

type ChannelType

type ChannelType string
const (
	ChannelTypeHeartbeats   ChannelType = "heartbeats"
	ChannelTypeCandles      ChannelType = "candles"
	ChannelTypeStatus       ChannelType = "status"
	ChannelTypeTicker       ChannelType = "ticker"
	ChannelTypeTickerBatch  ChannelType = "ticker_batch"
	ChannelTypeLevel2       ChannelType = "l2_data"
	ChannelTypeUser         ChannelType = "user"
	ChannelTypeMarketTrades ChannelType = "market_trades"
)

type CoinbaseError

type CoinbaseError struct {
	Error        string       `json:"error"`
	Code         string       `json:"code"`
	Message      string       `json:"message"`
	ErrorDetails string       `json:"error_details"`
	Details      ErrorDetails `json:"details"`
}

type ContractExpiryType

type ContractExpiryType string
const (
	ContractExpiryTypeExpiring ContractExpiryType = "EXPIRING"
	ContractExpiryTypeUnknown  ContractExpiryType = "UNKNOWN_CONTRACT"
)

type CreatOrderErrorResponse

type CreatOrderErrorResponse struct {
	Error                 string `json:"error"`
	Message               string `json:"message"`
	ErrorDetails          string `json:"error_details"`
	PreviewFailureReason  string `json:"preview_failure_reason"`
	NewOrderFailureReason string `json:"new_order_failure_reason"`
}

type CreateOrderData

type CreateOrderData struct {
	Success            bool                       `json:"success"`
	FailureReason      string                     `json:"failure_reason"`
	OrderId            string                     `json:"order_id"`
	SuccessResponse    CreateOrderSuccessResponse `json:"success_response"`
	ErrorResponse      CreatOrderErrorResponse    `json:"error_response"`
	OrderConfiguration OrderConfiguration         `json:"order_configuration"`
}

type CreateOrderRequest

type CreateOrderRequest struct {
	// ClientOrderId string Client set unique uuid for this order
	ClientOrderID string `json:"client_order_id"`
	// ProductId string The product this order was created for e.g. 'BTC-USD'
	ProductID string `json:"product_id"`
	// OrderType string Possible values: [UNKNOWN_ORDER_SIDE, BUY, SELL]
	Side               OrderSide          `json:"side"`
	OrderConfiguration OrderConfiguration `json:"order_configuration"`
}

func (CreateOrderRequest) ToJson

func (req CreateOrderRequest) ToJson() ([]byte, error)

type CreateOrderSuccessResponse

type CreateOrderSuccessResponse struct {
	OrderId       string `json:"order_id"`
	ProductId     string `json:"product_id"`
	Side          string `json:"side"`
	ClientOrderId string `json:"client_order_id"`
}

type Currencies

type Currencies struct {
	Data []struct {
		AssetId             string `json:"asset_id"`
		Code                string `json:"code"`
		Name                string `json:"name"`
		Color               string `json:"color"`
		SortIndex           int    `json:"sort_index"`
		Exponent            int    `json:"exponent"`
		Type                string `json:"type"`
		AddressRegex        string `json:"address_regex"`
		DestinationTagName  string `json:"destination_tag_name,omitempty"`
		DestinationTagRegex string `json:"destination_tag_regex,omitempty"`
	} `json:"data"`
}

Currencies represents a list of cryptocurrencies.

type CurrencyPairPrice

type CurrencyPairPrice struct {
	Data struct {
		Amount   string `json:"amount"`
		Currency string `json:"currency"`
	} `json:"data"`
}

CurrencyPairPrice represents the price of a currency pair.

type EditHistory

type EditHistory struct {
	Price                  string `json:"price"`
	Size                   string `json:"size"`
	ReplaceAcceptTimestamp string `json:"replace_accept_timestamp"`
}

type EditOrderData

type EditOrderData struct {
	Success bool            `json:"success"`
	Errors  EditOrderErrors `json:"errors"`
}

type EditOrderErrors

type EditOrderErrors struct {
	EditFailureReason    string `json:"edit_failure_reason"`
	PreviewFailureReason string `json:"preview_failure_reason"`
}

type EditOrderPreviewData

type EditOrderPreviewData struct {
	Errors             EditOrderErrors `json:"errors"`
	Slippage           string          `json:"slippage"`
	OrderTotal         string          `json:"order_total"`
	CommissionTotal    string          `json:"commission_total"`
	QuoteSize          string          `json:"quote_size"`
	BaseSize           string          `json:"base_size"`
	BestBid            string          `json:"best_bid"`
	BestAsk            string          `json:"best_ask"`
	AverageFilledPrice string          `json:"average_filled_price"`
}

type EditOrderRequest

type EditOrderRequest struct {
	// OrderId ID of order to edit.
	OrderId string `json:"order_id"`
	// Price New price of order. Required if order type is limit or stop-limit.
	Price string `json:"price"`
	// Size New size of order. Required if order type is limit or stop-limit.
	Size string `json:"size"`
}

func (EditOrderRequest) ToJson

func (req EditOrderRequest) ToJson() ([]byte, error)

type ErrorDetail

type ErrorDetail struct {
	TypeUrl string `json:"type_url"`
	Value   string `json:"value"`
}

type ErrorDetails

type ErrorDetails []ErrorDetail

func (*ErrorDetails) UnmarshalJSON

func (ed *ErrorDetails) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. Required because Coinbase returns an array of error details or a single error detail object.

type Event

type Event struct {
	Channel     string        `json:"channel"`
	ClientId    string        `json:"client_id"`
	Timestamp   time.Time     `json:"timestamp"`
	SequenceNum int           `json:"sequence_num"`
	Events      []interface{} `json:"events"`
}

Event represents a standard event message from the websocket connection.

func (Event) GetCandlesEvent

func (e Event) GetCandlesEvent() (CandlesEvent, error)

GetCandlesEvent converts a generic event to a candle event. Returns an error if the event is not a candle event.

func (Event) GetHeartbeatsEvent

func (e Event) GetHeartbeatsEvent() (HeartbeatsEvent, error)

GetHeartbeatsEvent converts a generic event to a heartbeat event. Returns an error if the event is not a heartbeat event.

func (Event) GetLevel2Event

func (e Event) GetLevel2Event() (Level2Event, error)

GetLevel2Event converts a generic event to a level 2 event. Returns an error if the event is not level 2 event.

func (Event) GetMarketTradesEvent

func (e Event) GetMarketTradesEvent() (MarketTradesEvent, error)

GetMarketTradesEvent converts a generic event to a market trades event. Returns an error if the event is not a market trades event.

func (Event) GetStatusEvent

func (e Event) GetStatusEvent() (StatusEvent, error)

GetStatusEvent converts a generic event to a status event. Returns an error if the event is not a status event.

func (Event) GetTickerEvent

func (e Event) GetTickerEvent() (TickerEvent, error)

GetTickerEvent converts a generic event to a ticker/ticket_batch event. Returns an error if the event is not a ticker/ticket_batch event.

func (Event) GetUserEvent

func (e Event) GetUserEvent() (UserEvent, error)

GetUserEvent converts a generic event to a user's order event. Returns an error if the event is not a user's order event.

func (Event) IsCandlesEvent

func (e Event) IsCandlesEvent() bool

IsCandlesEvent returns true if the event is a candle event.

func (Event) IsHeartbeatsEvent

func (e Event) IsHeartbeatsEvent() bool

IsHeartbeatsEvent returns true if the event is a heartbeat event.

func (Event) IsLevel2Event

func (e Event) IsLevel2Event() bool

IsLevel2Event returns true if the event is a level2 event.

func (Event) IsMarketTradesEvent

func (e Event) IsMarketTradesEvent() bool

IsMarketTradesEvent returns true if the event is a market trades event.

func (Event) IsStatusEvent

func (e Event) IsStatusEvent() bool

IsStatusEvent returns true if the event is a status event.

func (Event) IsTickerEvent

func (e Event) IsTickerEvent() bool

IsTickerEvent returns true if the event is a ticker event. TickerBatch has the same JSON message schema as the ticker channel, except the channel field will have a value of ticker_batch.

func (Event) IsUserEvent

func (e Event) IsUserEvent() bool

IsUserEvent returns true if the event is a user's order event.

type ExchangeRates

type ExchangeRates struct {
	Data struct {
		Currency string            `json:"currency"`
		Rates    map[string]string `json:"rates"`
	} `json:"data"`
}

ExchangeRates represents a list of exchange rates for a given currency.

type FcmTradingSessionDetails

type FcmTradingSessionDetails struct {
	IsSessionOpen string `json:"is_session_open"`
	OpenTime      string `json:"open_time"`
	CloseTime     string `json:"close_time"`
}

type FeeTier

type FeeTier struct {
	PricingTier  string `json:"pricing_tier"`
	UsdFrom      string `json:"usd_from"`
	UsdTo        string `json:"usd_to"`
	TakerFeeRate string `json:"taker_fee_rate"`
	MakerFeeRate string `json:"maker_fee_rate"`
	AopFrom      string `json:"aop_from"`
	AopTo        string `json:"aop_to"`
}

type FiatCurrencies

type FiatCurrencies struct {
	Data []struct {
		Id      string `json:"id"`
		Name    string `json:"name"`
		MinSize string `json:"min_size"`
	} `json:"data"`
}

FiatCurrencies represents a list of fiat currencies.

type Fill

type Fill struct {
	EntryId            string    `json:"entry_id"`
	TradeId            string    `json:"trade_id"`
	OrderId            string    `json:"order_id"`
	TradeTime          time.Time `json:"trade_time"`
	TradeType          string    `json:"trade_type"`
	Price              string    `json:"price"`
	Size               string    `json:"size"`
	Commission         string    `json:"commission"`
	ProductId          string    `json:"product_id"`
	SequenceTimestamp  time.Time `json:"sequence_timestamp"`
	LiquidityIndicator string    `json:"liquidity_indicator"`
	SizeInQuote        bool      `json:"size_in_quote"`
	UserId             string    `json:"user_id"`
	Side               string    `json:"side"`
}

type Fills

type Fills []Fill

func (*Fills) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface. Required because Coinbase returns an array of fills or a single fill object.

type FutureProductDetails

type FutureProductDetails struct {
	Venue                  string           `json:"venue"`
	ContractCode           string           `json:"contract_code"`
	ContractExpiry         string           `json:"contract_expiry"`
	ContractSize           string           `json:"contract_size"`
	ContractRootUnit       string           `json:"contract_root_unit"`
	GroupDescription       string           `json:"group_description"`
	ContractExpiryTimezone string           `json:"contract_expiry_timezone"`
	GroupShortDescription  string           `json:"group_short_description"`
	RiskManagedBy          string           `json:"risk_managed_by"`
	ContractExpiryType     string           `json:"contract_expiry_type"`
	PerpetualDetails       PerpetualDetails `json:"perpetual_details"`
	ContractDisplayName    string           `json:"contract_display_name"`
}

type GetAccountData

type GetAccountData struct {
	Account Account `json:"account"`
}

type GetOrderData

type GetOrderData struct {
	Order Order `json:"order"`
}

type GoodsAndServicesTax

type GoodsAndServicesTax struct {
	Rate string `json:"rate"`
	Type string `json:"type"`
}

type Granularity

type Granularity string
const (
	GranularityUnknown    Granularity = "UNKNOWN_GRANULARITY"
	GranularityOneMin     Granularity = "ONE_MINUTE"
	GranularityFiveMin    Granularity = "FIVE_MINUTE"
	GranularityFifteenMin Granularity = "FIFTEEN_MINUTE"
	GranularityThirtyMin  Granularity = "THIRTY_MINUTE"
	GranularityOneHour    Granularity = "ONE_HOUR"
	GranularityTwoHour    Granularity = "TWO_HOUR"
	GranularitySixHour    Granularity = "SIX_HOUR"
	GranularityOneDay     Granularity = "ONE_DAY"
)

type HeartbeatsEvent

type HeartbeatsEvent struct {
	Event
	Events []HeartbeatsEventType `json:"events"`
}

type HeartbeatsEventType

type HeartbeatsEventType struct {
	CurrentTime      string `json:"current_time" mapstructure:"current_time"`
	HeartbeatCounter string `json:"heartbeat_counter" mapstructure:"heartbeat_counter"`
}

type HttpClient

type HttpClient interface {
	Get(url string) (*req.Response, error)
	Post(url string, data []byte) (*req.Response, error)
	GetClient() *req.Client
}

func NewMockHttpClient

func NewMockHttpClient(resp *req.Response) HttpClient

type Level2Event

type Level2Event struct {
	Event
	Events []Level2EventType `json:"events"`
}

type Level2EventType

type Level2EventType struct {
	Type      string         `json:"type" mapstructure:"type"`
	ProductId string         `json:"product_id" mapstructure:"product_id"`
	Updates   []Level2Update `json:"updates" mapstructure:"updates"`
}

type Level2Update

type Level2Update struct {
	Side        string    `json:"side" mapstructure:"side"`
	EventTime   time.Time `json:"event_time" mapstructure:"event_time"`
	PriceLevel  string    `json:"price_level" mapstructure:"price_level"`
	NewQuantity string    `json:"new_quantity" mapstructure:"new_quantity"`
}

type LimitLimitGtc

type LimitLimitGtc struct {
	BaseSize   string `json:"base_size"`
	LimitPrice string `json:"limit_price"`
	PostOnly   bool   `json:"post_only"`
}

type LimitLimitGtd

type LimitLimitGtd struct {
	BaseSize   string    `json:"base_size"`
	LimitPrice string    `json:"limit_price"`
	EndTime    time.Time `json:"end_time"`
	PostOnly   bool      `json:"post_only"`
}

type ListAccountsData

type ListAccountsData struct {
	Accounts []Account `json:"accounts"`
	HasNext  bool      `json:"has_next"`
	Cursor   string    `json:"cursor"`
	Size     int       `json:"size"`
}

type ListFillsData

type ListFillsData struct {
	Fills  Fills  `json:"fills"`
	Cursor string `json:"cursor"`
}

type ListFillsQuery

type ListFillsQuery struct {
	// OrderId string ID of order
	OrderId string `json:"order_id"`
	// ProductId string The ID of the product this order was created for.
	ProductId string `json:"product_id"`
	// StartSequenceTimestamp date-time Start date. Only fills with a trade time at or after this start date are returned.
	StartSequenceTimestamp string `json:"start_sequence_timestamp"`
	// EndSequenceTimestamp date-time End date. Only fills with a trade time before this start date are returned.
	EndSequenceTimestamp string `json:"end_sequence_timestamp"`
	// Limit int64 Maximum number of fills to return in response. Defaults to 100.
	Limit int64 `json:"limit"`
	// Cursor string Cursor used for pagination. When provided, the response returns responses after this cursor.
	Cursor string `json:"cursor"`
}

ListFillsQuery represents the request parameters for the GetListFills function.

func (ListFillsQuery) BuildQueryString

func (q ListFillsQuery) BuildQueryString() string

BuildQueryString creates a query string from the request parameters. If no parameters are set, an empty string is returned.

type ListOrdersData

type ListOrdersData struct {
	Orders   Orders `json:"orders"`
	Sequence string `json:"sequence"`
	HasNext  bool   `json:"has_next"`
	Cursor   string `json:"cursor"`
}

type ListOrdersQuery

type ListOrdersQuery struct {
	// ProductId Optional string of the product ID. Defaults to null, or fetch for all products.
	ProductId string `json:"product_id,omitempty"`
	// OrderStatus A list of order statuses.
	OrderStatus []string `json:"order_status"`
	// Limit A pagination limit with no default set. If has_next is true, additional orders are available to be fetched with pagination.
	Limit int32 `json:"limit,omitempty"`
	// StartDate Start date to fetch orders from, inclusive.
	StartDate string `json:"start_date"`
	// EndDate An optional end date for the query window, exclusive.
	EndDate string `json:"end_date,omitempty"`
	// OrderType Type of orders to return. Default is to return all order types.
	OrderType OrderType `json:"order_type,omitempty"`
	// OrderSide Only orders matching this side are returned. Default is to return all sides.
	OrderSide OrderSide `json:"order_side,omitempty"`
	// Cursor used for pagination. When provided, the response returns responses after this cursor.
	Cursor string `json:"cursor,omitempty"`
	// ProductType Only orders matching this product type are returned. Default is to return all product types.
	ProductType ProductType `json:"product_type,omitempty"`
	// OrderPlacementSource Only orders matching this placement source are returned. Default is to return RETAIL_ADVANCED placement source.
	OrderPlacementSource OrderPlacementSource `json:"order_placement_source,omitempty"`
	// ContractExpiryType Only orders matching this contract expiry type are returned. Filter is only applied if ProductType is set to FUTURE in the request.
	ContractExpiryType ContractExpiryType `json:"contract_expiry_type,omitempty"`
}

ListOrdersQuery represents the request parameters for the GetListOrders function.

func (*ListOrdersQuery) BuildQueryString

func (q *ListOrdersQuery) BuildQueryString() string

BuildQueryString creates a query string from the request parameters. If no parameters are set, an empty string is returned.

type MarginRate

type MarginRate struct {
	Value string `json:"value"`
}

type MarketMarketIoc

type MarketMarketIoc struct {
	QuoteSize string `json:"quote_size"`
	BaseSize  string `json:"base_size"`
}

type MarketTrade

type MarketTrade struct {
	TradeId   string    `json:"trade_id" mapstructure:"trade_id"`
	ProductId string    `json:"product_id" mapstructure:"product_id"`
	Price     string    `json:"price" mapstructure:"price"`
	Size      string    `json:"size" mapstructure:"size"`
	Side      string    `json:"side" mapstructure:"side"`
	Time      time.Time `json:"time" mapstructure:"time"`
	Bid       string    `json:"bid"  mapstructure:"bid"`
	Ask       string    `json:"ask"  mapstructure:"ask"`
}

type MarketTradesData

type MarketTradesData struct {
	Trades  []MarketTrade `json:"trades"`
	BestBid string        `json:"best_bid"`
	BestAsk string        `json:"best_ask"`
}

type MarketTradesEvent

type MarketTradesEvent struct {
	Event
	Events []MarketTradesEventType `json:"events"`
}

type MarketTradesEventType

type MarketTradesEventType struct {
	Type   string        `json:"type"`
	Trades []MarketTrade `json:"trades"`
}

type MockHttpClient

type MockHttpClient struct {
	Response *req.Response
	Err      error
	// contains filtered or unexported fields
}

func (*MockHttpClient) Get

func (m *MockHttpClient) Get(url string) (*req.Response, error)

func (*MockHttpClient) GetClient

func (m *MockHttpClient) GetClient() *req.Client

func (*MockHttpClient) Post

func (m *MockHttpClient) Post(url string, data []byte) (*req.Response, error)

type Order

type Order struct {
	OrderId               string             `json:"order_id"`
	ProductId             string             `json:"product_id"`
	UserId                string             `json:"user_id"`
	OrderConfiguration    OrderConfiguration `json:"order_configuration"`
	Side                  string             `json:"side"`
	ClientOrderId         string             `json:"client_order_id"`
	Status                string             `json:"status"`
	TimeInForce           string             `json:"time_in_force"`
	CreatedTime           time.Time          `json:"created_time"`
	CompletionPercentage  string             `json:"completion_percentage"`
	FilledSize            string             `json:"filled_size"`
	AverageFilledPrice    string             `json:"average_filled_price"`
	Fee                   string             `json:"fee"`
	NumberOfFills         string             `json:"number_of_fills"`
	FilledValue           string             `json:"filled_value"`
	PendingCancel         bool               `json:"pending_cancel"`
	SizeInQuote           bool               `json:"size_in_quote"`
	TotalFees             string             `json:"total_fees"`
	SizeInclusiveOfFees   bool               `json:"size_inclusive_of_fees"`
	TotalValueAfterFees   string             `json:"total_value_after_fees"`
	TriggerStatus         string             `json:"trigger_status"`
	OrderType             string             `json:"order_type"`
	RejectReason          string             `json:"reject_reason"`
	Settled               string             `json:"settled"`
	ProductType           string             `json:"product_type"`
	RejectMessage         string             `json:"reject_message"`
	CancelMessage         string             `json:"cancel_message"`
	OrderPlacementSource  string             `json:"order_placement_source"`
	OutstandingHoldAmount string             `json:"outstanding_hold_amount"`
	IsLiquidation         string             `json:"is_liquidation"`
	LastFillTime          string             `json:"last_fill_time"`
	EditHistory           []EditHistory      `json:"edit_history"`
}

type OrderConfiguration

type OrderConfiguration struct {
	MarketMarketIoc       MarketMarketIoc       `json:"market_market_ioc"`
	LimitLimitGtc         LimitLimitGtc         `json:"limit_limit_gtc"`
	LimitLimitGtd         LimitLimitGtd         `json:"limit_limit_gtd"`
	StopLimitStopLimitGtc StopLimitStopLimitGtc `json:"stop_limit_stop_limit_gtc"`
	StopLimitStopLimitGtd StopLimitStopLimitGtd `json:"stop_limit_stop_limit_gtd"`
}

type OrderPlacementSource

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

type OrderSide

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

type OrderType

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

type Orders

type Orders []Order

func (*Orders) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface. Required because Coinbase returns an array of orders or a single order object.

type PerpetualDetails

type PerpetualDetails struct {
	OpenInterest string `json:"open_interest"`
	FundingRate  string `json:"funding_rate"`
	FundingTime  string `json:"funding_time"`
}

type PriceBook

type PriceBook struct {
	ProductId string           `json:"product_id"`
	Bids      []PriceBookOrder `json:"bids"`
	Asks      []PriceBookOrder `json:"asks"`
	Time      string           `json:"time"`
}

type PriceBookOrder

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

type Product

type Product struct {
	ProductId                 string                   `json:"product_id"`
	Price                     string                   `json:"price"`
	PricePercentageChange24H  string                   `json:"price_percentage_change_24h"`
	Volume24H                 string                   `json:"volume_24h"`
	VolumePercentageChange24H string                   `json:"volume_percentage_change_24h"`
	BaseIncrement             string                   `json:"base_increment"`
	QuoteIncrement            string                   `json:"quote_increment"`
	QuoteMinSize              string                   `json:"quote_min_size"`
	QuoteMaxSize              string                   `json:"quote_max_size"`
	BaseMinSize               string                   `json:"base_min_size"`
	BaseMaxSize               string                   `json:"base_max_size"`
	BaseName                  string                   `json:"base_name"`
	QuoteName                 string                   `json:"quote_name"`
	Watched                   bool                     `json:"watched"`
	IsDisabled                bool                     `json:"is_disabled"`
	New                       bool                     `json:"new"`
	Status                    string                   `json:"status"`
	CancelOnly                bool                     `json:"cancel_only"`
	LimitOnly                 bool                     `json:"limit_only"`
	PostOnly                  bool                     `json:"post_only"`
	TradingDisabled           bool                     `json:"trading_disabled"`
	AuctionMode               bool                     `json:"auction_mode"`
	ProductType               string                   `json:"product_type"`
	QuoteCurrencyId           string                   `json:"quote_currency_id"`
	BaseCurrencyId            string                   `json:"base_currency_id"`
	FcmTradingSessionDetails  FcmTradingSessionDetails `json:"fcm_trading_session_details"`
	MidMarketPrice            string                   `json:"mid_market_price"`
	Alias                     string                   `json:"alias"`
	AliasTo                   []string                 `json:"alias_to"`
	BaseDisplaySymbol         string                   `json:"base_display_symbol"`
	QuoteDisplaySymbol        string                   `json:"quote_display_symbol"`
	ViewOnly                  bool                     `json:"view_only"`
	PriceIncrement            string                   `json:"price_increment"`
	FutureProductDetails      FutureProductDetails     `json:"future_product_details"`
}

type ProductBookData

type ProductBookData struct {
	PriceBook PriceBook `json:"pricebook"`
}

type ProductCandles

type ProductCandles struct {
	Start  string `json:"start"`
	Low    string `json:"low"`
	High   string `json:"high"`
	Open   string `json:"open"`
	Close  string `json:"close"`
	Volume string `json:"volume"`
}

type ProductCandlesData

type ProductCandlesData struct {
	Candles []ProductCandles `json:"candles"`
}

type ProductStatus

type ProductStatus struct {
	ProductType    string `json:"product_type" mapstructure:"product_type"`
	Id             string `json:"id" mapstructure:"id"`
	BaseCurrency   string `json:"base_currency" mapstructure:"base_currency"`
	QuoteCurrency  string `json:"quote_currency" mapstructure:"quote_currency"`
	BaseIncrement  string `json:"base_increment" mapstructure:"base_increment"`
	QuoteIncrement string `json:"quote_increment" mapstructure:"quote_increment"`
	DisplayName    string `json:"display_name" mapstructure:"display_name"`
	Status         string `json:"status" mapstructure:"status"`
	StatusMessage  string `json:"status_message" mapstructure:"status_message"`
	MinMarketFunds string `json:"min_market_funds" mapstructure:"min_market_funds"`
}

type ProductType

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

type Products

type Products struct {
	Id                     string `json:"id"`
	BaseCurrency           string `json:"base_currency"`
	QuoteCurrency          string `json:"quote_currency"`
	QuoteIncrement         string `json:"quote_increment"`
	BaseIncrement          string `json:"base_increment"`
	DisplayName            string `json:"display_name"`
	MinMarketFunds         string `json:"min_market_funds"`
	MarginEnabled          bool   `json:"margin_enabled"`
	PostOnly               bool   `json:"post_only"`
	LimitOnly              bool   `json:"limit_only"`
	CancelOnly             bool   `json:"cancel_only"`
	Status                 string `json:"status"`
	StatusMessage          string `json:"status_message"`
	TradingDisabled        bool   `json:"trading_disabled"`
	FxStablecoin           bool   `json:"fx_stablecoin"`
	MaxSlippagePercentage  string `json:"max_slippage_percentage"`
	AuctionMode            bool   `json:"auction_mode"`
	HighBidLimitPercentage string `json:"high_bid_limit_percentage"`
}

type ReqClient

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

ReqClient is a wrapper around the req.Client to satisfy the HttpClient interface.

func (*ReqClient) Get

func (c *ReqClient) Get(url string) (*req.Response, error)

Get makes a GET request to the given URL.

func (*ReqClient) GetClient

func (c *ReqClient) GetClient() *req.Client

GetClient returns the underlying req.Client.

func (*ReqClient) Post

func (c *ReqClient) Post(url string, data []byte) (*req.Response, error)

Post makes a POST request to the given URL.

type ResponseError

type ResponseError struct {
	Message       string        `json:"message"`
	CoinbaseError CoinbaseError `json:"coinbase_error"`
}

func (ResponseError) Error

func (e ResponseError) Error() string

Implement the Error() method for MyCustomError. This method makes MyCustomError satisfy the error interface.

type ServerTime

type ServerTime struct {
	Data struct {
		Iso   time.Time `json:"iso"`
		Epoch int       `json:"epoch"`
	} `json:"data"`
}

type StatusEvent

type StatusEvent struct {
	Event
	Events []StatusEventType `json:"events"`
}

type StatusEventType

type StatusEventType struct {
	Type     string          `json:"type"`
	Products []ProductStatus `json:"products"`
}

type StopLimitStopLimitGtc

type StopLimitStopLimitGtc struct {
	BaseSize      string `json:"base_size"`
	LimitPrice    string `json:"limit_price"`
	StopPrice     string `json:"stop_price"`
	StopDirection string `json:"stop_direction"`
}

type StopLimitStopLimitGtd

type StopLimitStopLimitGtd struct {
	BaseSize      float64   `json:"base_size"`
	LimitPrice    string    `json:"limit_price"`
	StopPrice     string    `json:"stop_price"`
	EndTime       time.Time `json:"end_time"`
	StopDirection string    `json:"stop_direction"`
}

type SubType

type SubType string
const (
	SubTypeSubscribe   SubType = "subscribe"
	SubTypeUnsubscribe SubType = "unsubscribe"
)

type Ticker

type Ticker struct {
	Type               string `json:"type" mapstructure:"type"`
	ProductId          string `json:"product_id" mapstructure:"product_id"`
	Price              string `json:"price" mapstructure:"price"`
	Volume24H          string `json:"volume_24_h" mapstructure:"volume_24_h"`
	Low24H             string `json:"low_24_h" mapstructure:"low_24_h"`
	High24H            string `json:"high_24_h" mapstructure:"high_24_h"`
	Low52W             string `json:"low_52_w" mapstructure:"low_52_w"`
	High52W            string `json:"high_52_w" mapstructure:"high_52_w"`
	PricePercentChg24H string `json:"price_percent_chg_24_h" mapstructure:"price_percent_chg_24_h"`
}

Ticker represents a ticker from the websocket connection.

type TickerEvent

type TickerEvent struct {
	Event
	Events []TickerEventType `json:"events"`
}

TickerEvent represents a ticker event message from the websocket connection.

type TickerEventType

type TickerEventType struct {
	Type    string   `json:"type"`
	Tickers []Ticker `json:"tickers"`
}

type TransactionSummaryData

type TransactionSummaryData struct {
	TotalVolume             int                 `json:"total_volume"`
	TotalFees               int                 `json:"total_fees"`
	FeeTier                 FeeTier             `json:"fee_tier"`
	MarginRate              MarginRate          `json:"margin_rate"`
	GoodsAndServicesTax     GoodsAndServicesTax `json:"goods_and_services_tax"`
	AdvancedTradeOnlyVolume int                 `json:"advanced_trade_only_volume"`
	AdvancedTradeOnlyFees   int                 `json:"advanced_trade_only_fees"`
	CoinbaseProVolume       int                 `json:"coinbase_pro_volume"`
	CoinbaseProFees         int                 `json:"coinbase_pro_fees"`
}

type TransactionSummaryRequest

type TransactionSummaryRequest struct {
	// StartDate date-time RFC3339 format
	StartDate string
	// EndDate date-time RFC3339 format
	EndDate string
	// UserNativeCurrency string USD (default), EUR, GBP, etc. -- Only orders matching this native currency are returned.
	UserNativeCurrency string
	// ProductType string SPOT, FUTURE
	ProductType ProductType
	// ContractExpiryType string EXPIRING, UNKNOWN_CONTRACT (default) -- Only orders matching this contract expiry type are returned. Only filters response if ProductType is set to FUTURE.
	ContractExpiryType ContractExpiryType
}

type UserEvent

type UserEvent struct {
	Event
	Events []UserEventType `json:"events"`
}

type UserEventType

type UserEventType struct {
	Type   string      `json:"type"`
	Orders []UserOrder `json:"orders"`
}

type UserOrder

type UserOrder struct {
	OrderId            string    `json:"order_id" mapstructure:"order_id"`
	ClientOrderId      string    `json:"client_order_id" mapstructure:"client_order_id"`
	CumulativeQuantity string    `json:"cumulative_quantity" mapstructure:"cumulative_quantity"`
	LeavesQuantity     string    `json:"leaves_quantity" mapstructure:"leaves_quantity"`
	AvgPrice           string    `json:"avg_price" mapstructure:"avg_price"`
	TotalFees          string    `json:"total_fees" mapstructure:"total_fees"`
	Status             string    `json:"status" mapstructure:"status"`
	ProductId          string    `json:"product_id" mapstructure:"product_id"`
	CreationTime       time.Time `json:"creation_time" mapstructure:"creation_time"`
	OrderSide          string    `json:"order_side" mapstructure:"order_side"`
	OrderType          string    `json:"order_type" mapstructure:"order_type"`
}

type WebsocketChannel

type WebsocketChannel struct {
	Type       SubType     `json:"type"`
	ProductIds []string    `json:"product_ids"`
	Channel    ChannelType `json:"channel"`
	Signature  string      `json:"signature"`
	ApiKey     string      `json:"api_key"`
	SecretKey  string      `json:"-"`
	Timestamp  string      `json:"timestamp"`
}

func NewCandlesChannel

func NewCandlesChannel(productIds []string) WebsocketChannel

func NewChannelSubscribe

func NewChannelSubscribe(channel ChannelType, productIds []string) WebsocketChannel

func NewChannelUnsubscribe

func NewChannelUnsubscribe(channel ChannelType, productIds []string) WebsocketChannel

func NewHeartbeatsChannel

func NewHeartbeatsChannel(productIds []string) WebsocketChannel

func NewLevel2Channel

func NewLevel2Channel(productIds []string) WebsocketChannel

func NewStatusChannel

func NewStatusChannel(productIds []string) WebsocketChannel

func NewTickerBatchChannel

func NewTickerBatchChannel(productIds []string) WebsocketChannel

func NewTickerChannel

func NewTickerChannel(productIds []string) WebsocketChannel

func NewUserChannel

func NewUserChannel(productIds []string) WebsocketChannel

func NewWebsocketChannel

func NewWebsocketChannel(subType SubType, channel ChannelType, productIds []string) WebsocketChannel

type WsClient

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

WsClient is an automatically reconnecting websocket client.

func NewWsClient

func NewWsClient(cfg WsClientConfig) (*WsClient, error)

NewWsClient creates a new websocket client.

func (*WsClient) Connect

func (c *WsClient) Connect() (*websocket.Conn, error)

Connect connects to the websocket server.

func (*WsClient) ConnectWithUrl

func (c *WsClient) ConnectWithUrl(url string) (*websocket.Conn, error)

ConnectWithUrl connects to the websocket server using the provided url.

func (*WsClient) ReadChan

func (c *WsClient) ReadChan() chan []byte

ReadChan returns the channel that receives messages from the websocket connection.

func (*WsClient) Shutdown

func (c *WsClient) Shutdown()

Shutdown closes the websocket connection. This will also close the read channel and the underlying reconnect channel.

func (*WsClient) Write

func (c *WsClient) Write(data []byte) error

Write writes data to the websocket connection.

type WsClientConfig

type WsClientConfig struct {
	Url          string             // optional. defaults to "wss://advanced-trade-ws.coinbase.com"
	ReadChannel  chan []byte        // required for receiving messages from the websocket connection
	WsChannels   []WebsocketChannel // required for subscribing to innerChannels on the websocket connection
	ApiKey       string             // required for signing websocket messages
	SecretKey    string             // required for signing websocket messages
	OnConnect    func()             // optional. called when the websocket connection is established
	OnDisconnect func()             // optional. called when the websocket connection is closed
	OnReconnect  func()             // optional. called when the websocket connection is re-established
	UseBackoff   bool               // optional. defaults to false. uses an exponential backoff strategy with jitter
	Debug        bool               // optional. defaults to false. prints debug messages
}

WsClientConfig is the configuration struct for creating a new websocket client.

func NewWsClientConfig

func NewWsClientConfig(apiKey, secretKey string, readCh chan []byte, wsChannels []WebsocketChannel) WsClientConfig

Jump to

Keyboard shortcuts

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