当前位置: 首页 > 软件库 > Web3 > 开源货币/比特币 >

go-coinbasepro

授权协议 MIT License
开发语言 Python
所属分类 Web3、 开源货币/比特币
软件类型 开源软件
地区 不详
投 递 者 厉念
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Go Coinbase Pro

Summary

Go client for CoinBase Pro formerly known as gdax

Installation

If using Go modules (Go version >= 11.1) simply import as needed.

go mod init github.com/yourusername/yourprojectname

Older Go versions

go get github.com/preichenberger/go-coinbasepro

Significant releases

Use dep to install previous releases

dep ensure --add github.com/preichenberger/go-gdax@0.5.7
  • 0.5.7, last release before rename package to: coinbasepro
  • 0.5, as of 0.5 this library uses strings and is not backwards compatible

Documentation

For full details on functionality, see GoDoc documentation.

Setup

Client will respect environment variables: COINBASE_PRO_BASEURL, COINBASE_PRO_PASSPHRASE, COINBASE_PRO_KEY, COINBASE_PRO_SECRET by default

import (
  coinbasepro "github.com/preichenberger/go-coinbasepro/v2"
)

client := coinbasepro.NewClient()

// optional, configuration can be updated with ClientConfig
client.UpdateConfig(&coinbasepro.ClientConfig{
  BaseURL: "https://api.pro.coinbase.com",
  Key: "coinbase pro key",
  Passphrase: "coinbase pro passphrase",
  Secret: "coinbase pro secret",
})

Sandbox

You can switch to the sandbox URL by setting environment variable: COINBASE_PRO_SANDBOX

Enable sandbox

export COINBASE_PRO_SANDBOX=1

Disable sandbox

export COINBASE_PRO_SANDBOX=0

HTTP Settings

import (
  "net/http"
  "time"
)

client.HTTPClient = &http.Client {
  Timeout: 15 * time.Second,
}

Decimals

To manage precision correctly, this library sends all price values as strings. It is recommended to use a decimal librarylike Spring's Decimal if you are doing any manipulation of prices.

Example:

import (
  "github.com/shopspring/decimal"
)

book, err := client.GetBook("BTC-USD", 1)
if err != nil {
    println(err.Error())  
}

lastPrice, err := decimal.NewFromString(book.Bids[0].Price)
if err != nil {
    println(err.Error())  
}

order := coinbasepro.Order{
  Price: lastPrice.Add(decimal.NewFromFloat(1.00)).String(),
  Size: "2.00",
  Side: "buy",
  ProductID: "BTC-USD",
}

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

println(savedOrder.ID)

Retry

You can set a retry count which uses exponential backoff: (2^(retry_attempt) - 1) / 2 * 1000 * milliseconds

client.RetryCount = 3 # 500ms, 1500ms, 3500ms

Cursor

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

var orders []coinbasepro.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.pro.coinbase.com", nil)
  if err != nil {
    println(err.Error())
  }

  subscribe := coinbasepro.Message{
    Type:      "subscribe",
    Channels: []coinbasepro.MessageChannel{
      coinbasepro.MessageChannel{
        Name: "heartbeat",
        ProductIds: []string{
          "BTC-USD",
        },
      },
      coinbasepro.MessageChannel{
        Name: "level2",
        ProductIds: []string{
          "BTC-USD",
        },
      },
    },
  }
  if err := wsConn.WriteJSON(subscribe); err != nil {
    println(err.Error())
  }

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

    println(message.Type)
  }

Time

Results return coinbase time type which handles different types of time parsing that coinbasepro returns. This wraps the native go time type

import(
    "time"
    coinbasepro "github.com/preichenberger/go-coinbasepro/v2"
  )

  coinbaseTime := coinbasepro.Time{}
  println(time.Time(coinbaseTime).Day())

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 ledgers []coinbasepro.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(&ledgers); err != nil {
        println(err.Error())
      }

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

Create an Order:

order := coinbasepro.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 := coinbasepro.Transfer {
    Type: "deposit",
    Amount: "1.00",
  }

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

Get Trade history:

var trades []coinbasepro.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:

export COINBASE_PRO_KEY="sandbox key"
export COINBASE_PRO_PASSPHRASE="sandbox passphrase"
export COINBASE_PRO_SECRET="sandbox secret"

Then run go test

go test

Note that your sandbox account will need at least 2,000 USD and 2 BTC to run the tests.

 相关资料
  • Go!

    Go! 是一个 PHP 5.4 库,让 PHP 支持 AOP 面向方面编程方法,无需 PECL 扩展、Runkit、evals 或者 DI 容器支持。可使用 XDebug 轻松调试。 示例代码: // Aspect/MonitorAspect.phpnamespace Aspect;use Go\Aop\Aspect;use Go\Aop\Intercept\FieldAccess;use Go\

  • 命令go vet是一个用于检查Go语言源码中静态错误的简单工具。与大多数Go命令一样,go vet命令可以接受-n标记和-x标记。-n标记用于只打印流程中执行的命令而不真正执行它们。-n标记也用于打印流程中执行的命令,但不会取消这些命令的执行。示例如下: hc@ubt:~$ go vet -n pkgtool /usr/local/go/pkg/tool/linux_386/vet golang/

  • 命令go fix会把指定代码包的所有Go语言源码文件中的旧版本代码修正为新版本的代码。这里所说的版本即Go语言的版本。代码包的所有Go语言源码文件不包括其子代码包(如果有的话)中的文件。修正操作包括把对旧程序调用的代码更换为对新程序调用的代码、把旧的语法更换为新的语法,等等。 这个工具其实非常有用。在编程语言的升级和演进的过程中,难免会对过时的和不够优秀的语法及标准库进行改进。这样的改进对于编程语

  • Pact Go的版本目前支持Pact v2规范,访问网站开始学习。 Go-Kit例子 Pact Go代码库中有一个详细的Go Kit 例子,介绍如何使用Pact去测试Go Kit微服务。 原生Go实现 还有一个Go版本的Pact(兼容pact v1.1),不需要运行一个守护进程。如果你不需要v2+的匹配以及运行守护进程,可以考虑使用或者为Pact Go贡献。

  • Panic表示的意思就是有些意想不到的错误发生了。通常我们用来表示程序正常运行过程中不应该出现的,或者我们没有处理好的错误。 package main import "os" func main() { // 我们使用panic来检查预期不到的错误 panic("a problem") // Panic的通常使用方法就是如果一个函数 // 返回一个我们不知道怎么处理

  • 使用os.Exit可以给定一个状态,然后立刻退出程序运行。 package main import "fmt" import "os" func main() { // 当使用`os.Exit`的时候defer操作不会被运行, // 所以这里的``fmt.Println`将不会被调用 defer fmt.Println("!") // 退出程序并设置退出状态值