coinbase

package module
v0.0.0-...-e48e443 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2023 License: Apache-2.0 Imports: 14 Imported by: 0

README

Coinbase Go Library

PkgGoDev Build Status Go Report Card Discord

Coinbase is a Go library that provides a simple and convenient way to interact with the Coinbase API. It wraps the Coinbase API endpoints and handles authentication for you, so you can focus on building your application.

Installation

go get github.com/alpstable/coinbase

Contributing

To work on the Coinbase Go Library, you need to have the following requirements installed on your system:

  1. go: https://go.dev/doc/install
  2. golangci-lint: https://golangci-lint.run/usage/install/
  3. gofumpt: https://github.com/mvdan/gofumpt

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrStatusNotOK = errors.New("status not OK")

ErrStatusNotOK is returned when the Coinbase API returns a non-OK status code.

Functions

This section is empty.

Types

type Account

type Account struct {
	UUID             string         `json:"uuid"`
	Name             string         `json:"name"`
	Currency         string         `json:"currency"`
	AvailableBalance AvailableMoney `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,omitempty"`
	Type             string         `json:"type"`
	Ready            bool           `json:"ready"`
	Hold             HoldMoney      `json:"hold"`
}

Account represents a user account with the available balance and hold amount of currency.

type Accounts

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

Accounts represents a collection of accounts along with metadata.

type AvailableMoney

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

AvailableMoney represents an amount of money that is available.

type Client

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

Client is a Coinbase API client.

func NewClient

func NewClient(key, secret string) (*Client, error)

NewClient creates a new Coinbase API client with the provided API key and secret. The Coinbase API requests are automatically signed with the provided API key and secret using an http Transport middleware.

func (*Client) Accounts

func (client *Client) Accounts(ctx context.Context) (*Accounts, error)

Accounts returns a slice of accounts for the authenticated user.

https://docs.cloud.coinbase.com/advanced-trade-api/reference/retailbrokerageapi_getaccounts

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/alpstable/coinbase"
)

func main() {
	// DO NOT RUN THIS EXAMPLE ON A LIVE ACCOUNT
	key := os.Getenv("COINBASE_API_KEY")
	secret := os.Getenv("COINBASE_API_SECRET")

	if key == "" || secret == "" {
		log.Println("COINBASE_API_KEY or COINBASE_API_SECRET is empty")

		return
	}

	client, err := coinbase.NewClient(key, secret)
	if err != nil {
		panic(err)
	}

	accounts, err := client.Accounts(context.Background())
	if err != nil {
		panic(err)
	}

	log.Printf("accounts: %+v", accounts)
}
Output:

func (*Client) CreateOrder

func (client *Client) CreateOrder(ctx context.Context, orderReq OrderRequest) (*Order, error)

CreateOrder will create an order with a specified product_id (BASE-QUOTE), side (buy/sell), etc.

https://docs.cloud.coinbase.com/advanced-trade-api/reference/retailbrokerageapi_postorder

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/alpstable/coinbase"
	"github.com/google/uuid"
)

func main() {
	// DO NOT RUN THIS EXAMPLE ON A LIVE ACCOUNT
	key := os.Getenv("COINBASE_API_KEY")
	secret := os.Getenv("COINBASE_API_SECRET")

	if key == "" || secret == "" {
		log.Println("COINBASE_API_KEY or COINBASE_API_SECRET is empty")

		return
	}

	client, err := coinbase.NewClient(key, secret)
	if err != nil {
		panic(err)
	}

	limit := &coinbase.LimitGTCConfig{
		BaseSize: "1",
		Price:    "2.7",
	}

	confg := coinbase.OrderConfig{
		LimitGTC: limit,
	}

	req := coinbase.OrderRequest{
		ClientOrderID: uuid.New().String(),
		ProductID:     "BTC-USDT",
		Side:          coinbase.OrderSideBuy,
		Configuration: confg,
	}

	// Buy 1 BTC at 2.7 USDT
	orderResponse, err := client.CreateOrder(context.Background(), req)
	if err != nil {
		panic(err)
	}

	log.Printf("orderResponse: %+v", orderResponse)
}
Output:

type ErrorResponse

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

ErrorResponse represents an error response.

type HoldMoney

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

HoldMoney represents an amount of money that is being held.

type LimitGTCConfig

type LimitGTCConfig struct {
	BaseSize string `json:"base_size" validate:"required"`
	Price    string `json:"limit_price" validate:"required"`
	PostOnly bool   `json:"post_only"`
}

LimitGTCConfig represents the configuration of a good-'til-cancelled limit order.

type LimitGTDConfig

type LimitGTDConfig struct {
	BaseSize string    `json:"base_size" validate:"required"`
	Price    string    `json:"limit_price" validate:"required"`
	EndTime  time.Time `json:"end_time" validate:"required"`
	PostOnly bool      `json:"post_only"`
}

LimitGTDConfig represents the configuration of a good-'til-date limit order.

type MarketIOCConfig

type MarketIOCConfig struct {
	QuoteSize string `json:"quote_size" validate:"required_if=Side:BUY"`
	BaseSize  string `json:"base_size" validate:"required_if=Side:SELL"`
}

MarketIOCConfig represents the configuration of a market or immediate-or-cancel order.

type Order

type Order struct {
	Success            bool            `json:"success"`
	FailureReason      string          `json:"failure_reason"`
	OrderID            string          `json:"order_id"`
	SuccessResponse    SuccessResponse `json:"success_response,omitempty"`
	ErrorResponse      ErrorResponse   `json:"error_response,omitempty"`
	OrderConfiguration OrderConfig     `json:"order_configuration,omitempty"`
}

Order is the response from creating an order.

type OrderConfig

type OrderConfig struct {
	MarketIOC    *MarketIOCConfig    `json:"market_market_ioc,omitempty"`
	LimitGTC     *LimitGTCConfig     `json:"limit_limit_gtc,omitempty"`
	LimitGTD     *LimitGTDConfig     `json:"limit_limit_gtd,omitempty"`
	StopLimitGTC *StopLimitGTCConfig `json:"stop_limit_stop_limit_gtc,omitempty"`
	StopLimitGTD *StopLimitGTDConfig `json:"stop_limit_stop_limit_gtd,omitempty"`
}

OrderConfig represents the configuration of an order.

type OrderRequest

type OrderRequest struct {
	ClientOrderID string      `json:"client_order_id" validate:"required"`
	ProductID     string      `json:"product_id" validate:"required"`
	Side          OrderSide   `json:"side"`
	Configuration OrderConfig `json:"order_configuration"`
}

OrderRequest can be used to create an order on Coinbase.

type OrderSide

type OrderSide string

OrderSide represents the side of an order, either BUY or SELL.

const (
	// OrderSideUnknown represents an unknown or undefined order side.
	OrderSideUnknown OrderSide = "UNKNOWN_ORDER_SIDE"

	// OrderSideBuy represents a buy order side.
	OrderSideBuy OrderSide = "BUY"

	// OrderSideSell represents a sell order side.
	OrderSideSell OrderSide = "SELL"
)

type OrderStopDirection

type OrderStopDirection string

OrderStopDirection represents the possible stop directions for an order.

const (
	// StopDirUnknown represents an unknown stop direction for an order.
	StopDirUnknown OrderStopDirection = "UNKNOWN_STOP_DIRECTION"

	// StopDirUp represents a stop direction for an order that triggers if
	// the price goes up.
	StopDirUp OrderStopDirection = "STOP_DIRECTION_STOP_UP"

	// StopDirDown represents a stop direction for an order that triggers if
	// the price goes down.
	StopDirDown OrderStopDirection = "STOP_DIRECTION_STOP_DOWN"
)

type StopLimitGTCConfig

type StopLimitGTCConfig struct {
	BaseSize      string             `json:"base_size" validate:"required"`
	LimitPrice    string             `json:"limit_price" validate:"required"`
	StopPrice     string             `json:"stop_price" validate:"required"`
	StopDirection OrderStopDirection `json:"stop_direction"`
}

StopLimitGTCConfig represents a stop-limit order with Good-til-Canceled time in force.

type StopLimitGTDConfig

type StopLimitGTDConfig struct {
	BaseSize      string             `json:"base_size" validate:"required"`
	LimitPrice    string             `json:"limit_price" validate:"required"`
	StopPrice     string             `json:"stop_price" validate:"required"`
	StopDirection OrderStopDirection `json:"stop_direction"`
	EndTime       time.Time          `json:"end_time" validate:"required"`
}

StopLimitGTDConfig represents a stop-limit order with Good-til-Date time in force.

type SuccessResponse

type SuccessResponse struct {
	OrderID       string    `json:"order_id"`
	ProductID     string    `json:"product_id,omitempty"`
	Side          OrderSide `json:"side,omitempty"`
	ClientOrderID string    `json:"client_order_id,omitempty"`
}

SuccessResponse represents a successful order response.

Jump to

Keyboard shortcuts

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