coinbase

package module
v0.0.0-...-78b289a Latest Latest
Warning

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

Go to latest
Published: May 15, 2018 License: MIT Imports: 15 Imported by: 0

README

Go Coinbase Exchange GoDoc Build Status

Summary

Go client for Coinbase Exchange

Installation

go get github.com/preichenberger/go-coinbase-exchange

Documentation

For full details on functionality, see GoDoc documentation.

Setup

How to create a client:


import (
  "os"
  exchange "github.com/preichenberger/go-coinbase-exchange"
)

secret := os.Getenv("COINBASE_SECRET") 
key := os.Getenv("COINBASE_KEY") 
passphrase := os.Getenv("COINBASE_PASSPHRASE") 

// or unsafe hardcode way
secret = "exposedsecret"
key = "exposedkey"
passphrase = "exposedpassphrase"

client := exchange.NewClient(secret, key, passphrase)
Cursor

This library uses a cursor pattern so you don't have to keep track of pagination.

var orders []exchange.Order
cursor = client.ListOrders()

for cursor.HasMore {
  if err := cursor.NextPage(&orders); err != nil {
    println(err.Error())
    return
  }

  for _, o := range orders {
    println(o.Id) 
  }
}

Websockets

Listen for websocket messages

  import(
    ws "github.com/gorilla/websocket"
  )

  var wsDialer ws.Dialer
  wsConn, _, err := wsDialer.Dial("wss://ws-feed.exchange.coinbase.com", nil)
  if err != nil {
    println(err.Error())
  }

  subscribe := map[string]string{
    "type": "subscribe",
    "product_id": "BTC-USD",
  }
  if err := wsConn.WriteJSON(subscribe); err != nil {
    println(err.Error())
  }

  message:= exchange.Message{}
  for true {
    if err := wsConn.ReadJSON(&message); err != nil {
      println(err.Error())
      break
    }

    if message.Type == "match" {
      println("Got a match")
    }
  }

Examples

This library supports all public and private endpoints

Get Accounts:

  accounts, err := client.GetAccounts()
  if err != nil {
    println(err.Error())
  }

  for _, a := range accounts {
    println(a.Balance)
  }

List Account Ledger:

  var ledger []exchange.LedgerEntry

  accounts, err := client.GetAccounts()
  if err != nil {
    println(err.Error())
  }

  for _, a := range accounts {
    cursor := client.ListAccountLedger(a.Id)
    for cursor.HasMore {
      if err := cursor.NextPage(&ledger); err != nil {
        println(err.Error())
      }

      for _, e := range ledger {
        println(e.Amount)
      }
  }

Create an Order:

  order := exchange.Order{
    Price: 1.00,   
    Size: 1.00,   
    Side: "buy",   
    ProductId: "BTC-USD",   
  }

  savedOrder, err := client.CreateOrder(&order)
  if err != nil {
    println(err.Error())
  }

  println(savedOrder.Id)

Transfer funds:

  transfer := exchange.Transfer {
    Type: "deposit",
    Amount: 1.00,   
  }

  savedTransfer, err := client.CreateTransfer(&transfer)
  if err != nil {
    println(err.Error())
  }

Get Trade history:

  var trades []exchange.Trade
  cursor := client.ListTrades("BTC-USD")

  for cursor.HasMore {
    if err := cursor.NextPage(&trades); err != nil {
      for _, t := range trades {
        println(trade.CoinbaseId)
      }
    } 
  }
Testing

To test with Coinbase's public sandbox set the following environment variables:

  • TEST_COINBASE_SECRET
  • TEST_COINBASE_KEY
  • TEST_COINBASE_PASSPHRASE

Then run go test

TEST_COINBASE_SECRET=secret TEST_COINBASE_KEY=key TEST_COINBASE_PASSPHRASE=passphrase go test

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareProperties

func CompareProperties(a, b interface{}, properties []string) (bool, error)

func StructHasZeroValues

func StructHasZeroValues(i interface{}) bool

Types

type Account

type Account struct {
	Id        string  `json:"id"`
	Balance   float64 `json:"balance,string"`
	Hold      float64 `json:"hold,string"`
	Available float64 `json:"available,string"`
	Currency  string  `json:"currency"`
}

type Book

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

type BookEntry

type BookEntry struct {
	Price          float64
	Size           float64
	NumberOfOrders int
	OrderId        string
}

func (*BookEntry) UnmarshalJSON

func (e *BookEntry) UnmarshalJSON(data []byte) error

type Client

type Client struct {
	BaseURL    string
	Secret     string
	Key        string
	Passphrase string
}

func NewClient

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

func NewTestClient

func NewTestClient() *Client

func (*Client) CancelOrder

func (c *Client) CancelOrder(id string) error

func (*Client) CreateOrder

func (c *Client) CreateOrder(newOrder *Order) (Order, error)

func (*Client) CreateReport

func (c *Client) CreateReport(newReport *Report) (Report, error)

func (*Client) CreateTransfer

func (c *Client) CreateTransfer(newTransfer *Transfer) (Transfer, error)

func (*Client) GetAccount

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

func (*Client) GetAccounts

func (c *Client) GetAccounts() ([]Account, error)

Client Funcs

func (*Client) GetBook

func (c *Client) GetBook(product string, level int) (Book, error)

func (*Client) GetCurrencies

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

func (*Client) GetHistoricRates

func (c *Client) GetHistoricRates(product string,
	p ...GetHistoricRatesParams) ([]HistoricRate, error)

func (*Client) GetOrder

func (c *Client) GetOrder(id string) (Order, error)

func (*Client) GetProducts

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

func (*Client) GetReportStatus

func (c *Client) GetReportStatus(id string) (Report, error)

func (*Client) GetStats

func (c *Client) GetStats(product string) (Stats, error)

func (*Client) GetTicker

func (c *Client) GetTicker(product string) (Ticker, error)

func (*Client) GetTime

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

func (*Client) ListAccountLedger

func (c *Client) ListAccountLedger(id string,
	p ...GetAccountLedgerParams) *Cursor

func (*Client) ListFills

func (c *Client) ListFills(p ...ListFillsParams) *Cursor

func (*Client) ListHolds

func (c *Client) ListHolds(id string, p ...ListHoldsParams) *Cursor

func (*Client) ListOrders

func (c *Client) ListOrders(p ...ListOrdersParams) *Cursor

func (*Client) ListTrades

func (c *Client) ListTrades(product string,
	p ...ListTradesParams) *Cursor

func (*Client) Request

func (c *Client) Request(method string, url string,
	params, result interface{}) (res *http.Response, err error)

type CreateReportParams

type CreateReportParams struct {
	Start time.Time
	End   time.Time
}

type Currency

type Currency struct {
	Id      string  `json:"id"`
	Name    string  `json:"name"`
	MinSize float64 `json:"min_size,string"`
}

type Cursor

type Cursor struct {
	Client     *Client
	Pagination *PaginationParams
	Method     string
	Params     interface{}
	URL        string
	HasMore    bool
}

func NewCursor

func NewCursor(client *Client, method, url string,
	paginationParams *PaginationParams) *Cursor

func (*Cursor) NextPage

func (c *Cursor) NextPage(i interface{}) error

type Error

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

func (Error) Error

func (e Error) Error() string

type Fill

type Fill struct {
	TradeId   int     `json:"trade_id,int"`
	ProductId string  `json:"product_id"`
	Price     float64 `json:"price,string"`
	Size      float64 `json:"size,string"`
	FillId    string  `json:"order_id"`
	CreatedAt Time    `json:"created_at,string"`
	Fee       float64 `json:"fee,string"`
	Settled   bool    `json:"settled"`
	Side      string  `json:"side"`
	Liquidity string  `json:"liquidity"`
}

type GetAccountLedgerParams

type GetAccountLedgerParams struct {
	Pagination PaginationParams
}

type GetHistoricRatesParams

type GetHistoricRatesParams struct {
	Start       time.Time
	End         time.Time
	Granularity int
}

type HistoricRate

type HistoricRate struct {
	Time   time.Time
	Low    float64
	High   float64
	Open   float64
	Close  float64
	Volume float64
}

func (*HistoricRate) UnmarshalJSON

func (e *HistoricRate) UnmarshalJSON(data []byte) error

type Hold

type Hold struct {
	AccountId string  `json:"account_id"`
	CreatedAt Time    `json:"created_at,string"`
	UpdatedAt Time    `json:"updated_at,string"`
	Amount    float64 `json:"amount,string"`
	Type      string  `json:"type"`
	Ref       string  `json:"ref"`
}

type LedgerDetails

type LedgerDetails struct {
	OrderId   string `json:"order_id"`
	TradeId   string `json:"trade_id"`
	ProductId string `json:"product_id"`
}

type LedgerEntry

type LedgerEntry struct {
	Id        int           `json:"id,number"`
	CreatedAt Time          `json:"created_at,string"`
	Amount    float64       `json:"amount,string"`
	Balance   float64       `json:"balance,string"`
	Type      string        `json:"type"`
	Details   LedgerDetails `json:"details"`
}

type ListFillsParams

type ListFillsParams struct {
	OrderId    string
	ProductId  string
	Pagination PaginationParams
}

type ListHoldsParams

type ListHoldsParams struct {
	Pagination PaginationParams
}

type ListOrdersParams

type ListOrdersParams struct {
	Status     string
	Pagination PaginationParams
}

type ListTradesParams

type ListTradesParams struct {
	Pagination PaginationParams
}

type Message

type Message struct {
	Type          string  `json:"type"`
	TradeId       int     `json:"trade_id,number"`
	OrderId       string  `json:"order_id"`
	Sequence      int     `json:"sequence,number"`
	MakerOrderId  string  `json:"maker_order_id"`
	TakerOrderId  string  `json:"taker_order_id"`
	Time          Time    `json:"time,string"`
	RemainingSize float64 `json:"remaining_size,string"`
	NewSize       float64 `json:"new_size,string"`
	OldSize       float64 `json:"old_size,string"`
	Size          float64 `json:"size,string"`
	Price         float64 `json:"price,string"`
	Side          string  `json:"side"`
	Reason        string  `json:"reason"`
	OrderType     string  `json:"order_type"`
	Funds         float64 `json:"funds,string"`
	NewFunds      float64 `json:"new_funds,string"`
	OldFunds      float64 `json:"old_funds,string"`
	ProductId     string  `json:"product_id"`
}

type Order

type Order struct {
	Type      string  `json:"type"`
	Size      float64 `json:"size,string"`
	Side      string  `json:"side"`
	ProductId string  `json:"product_id"`
	ClientOID string  `json:"client_oid,omitempty"`
	Stp       string  `json:"stp,omitempty"`
	// Limit Order
	Price       float64 `json:"price,string,omitempty"`
	TimeInForce string  `json:"time_in_force,omitempty"`
	PostOnly    bool    `json:"post_only,omitempty"`
	// Market Order
	Funds float64 `json:"funds,string,omitempty"`
	// Response Fields
	Id         string `json:"id"`
	Status     string `json:"status,omitempty"`
	Settled    bool   `json:"settled,omitempty"`
	DoneReason string `json:"done_reason,omitempty"`
	CreatedAt  Time   `json:"created_at,string,omitempty"`
}

type PaginationParams

type PaginationParams struct {
	Limit  int
	Before string
	After  string
	Extra  map[string]string
}

func (*PaginationParams) AddExtraParam

func (p *PaginationParams) AddExtraParam(key, value string)

func (*PaginationParams) Done

func (p *PaginationParams) Done() bool

func (*PaginationParams) Encode

func (p *PaginationParams) Encode(direction string) string

type Product

type Product struct {
	Id             string  `json:"id"`
	BaseCurency    string  `json:"base_currency"`
	QuoteCurrency  string  `json:"quote_currency"`
	BaseMinSize    float64 `json:"base_min_size,string"`
	BaseMaxSize    float64 `json:"base_max_size,string"`
	QuoteIncrement float64 `json:"quote_increment,string"`
	DisplayName    string  `json:"display_name"`
}

type Report

type Report struct {
	Id          string       `json:"id"`
	Type        string       `json:"type"`
	Status      string       `json:"status"`
	CreatedAt   Time         `json:"created_at,string"`
	CompletedAt Time         `json:"completed_at,string,"`
	ExpiresAt   Time         `json:"expires_at,string"`
	FileURL     string       `json:"file_url"`
	Params      ReportParams `json:"params"`
	StartDate   time.Time
	EndDate     time.Time
}

type ReportParams

type ReportParams struct {
	StartDate time.Time
	EndDate   time.Time
}

type ServerTime

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

type Stats

type Stats struct {
	Low    float64 `json:"low,string"`
	High   float64 `json:"high,string"`
	Open   float64 `json:"open,string"`
	Volume float64 `json:"volume,string"`
}

type Ticker

type Ticker struct {
	TradeId int     `json:"trade_id,number"`
	Price   float64 `json:"price,string"`
	Size    float64 `json:"size,string"`
	Time    Time    `json:"time,string"`
}

type Time

type Time time.Time

func (*Time) Time

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

func (*Time) UnmarshalJSON

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

type Trade

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

type Transfer

type Transfer struct {
	Type              string  `json:"type"`
	Amount            float64 `json:"amount,string"`
	CoinbaseAccountId string  `json:"coinbase_account_id,string"`
}

Jump to

Keyboard shortcuts

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