Go Binance
最后修改时间 2024 年 4 月 11 日
在本文中,我们将展示如何使用 go-binance 包在 Go 中处理 Binance 交易所。
go-binance 是一个非官方的 Golang Binance API SDK。Binance 是一个流行的加密货币交易所。Binance 同时提供公共 API 和私有 API。对于私有 API,我们需要提供 API 密钥。
Golang Binance 交易对列表
交易对是一个交易品种。它由基础资产和计价资产组成。给定一个交易对 LTCBUSD,LTC 代表基础资产,BUSD 代表计价资产。
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/adshao/go-binance/v2"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
res, err := client.NewExchangeInfoService().Symbols().Do(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Println(len(res.Symbols))
for _, e := range res.Symbols {
fmt.Printf("%s %s %s %s\n", e.Symbol, e.Status, e.BaseAsset, e.QuoteAsset)
}
}
在程序中,我们将列出 Binance 上所有可用的交易对。
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
我们初始化客户端。密钥存储在环境变量中。
res, err := client.NewExchangeInfoService().Symbols().Do(context.Background())
我们调用 NewExchangeInfoService 服务。
for _, e := range res.Symbols {
fmt.Printf("%s %s %s %s\n", e.Symbol, e.Status, e.BaseAsset, e.QuoteAsset)
}
我们遍历列表并将它们打印到控制台。我们打印交易对名称、状态、基础资产和计价资产。
$ go run main.go 2206 ETHBTC TRADING ETH BTC LTCBTC TRADING LTC BTC BNBBTC TRADING BNB BTC NEOBTC TRADING NEO BTC ...
Golang Binance 检查余额
在下一个示例中,我们将查看资产余额。
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"github.com/adshao/go-binance/v2"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
res, err := client.NewGetAccountService().Do(context.Background())
if err != nil {
log.Fatal(err)
}
for _, e := range res.Balances {
free, _ := strconv.ParseFloat(e.Free, 32)
locked, _ := strconv.ParseFloat(e.Locked, 32)
if free > 0 || locked > 0 {
fmt.Printf("%-5s %18f %10f\n", e.Asset, free, locked)
}
}
}
在程序中,我们检查所有大于 0 的资产余额。
res, err := client.NewGetAccountService().Do(context.Background())
我们调用 NewGetAccountService。
for _, e := range res.Balances {
free, _ := strconv.ParseFloat(e.Free, 32)
locked, _ := strconv.ParseFloat(e.Locked, 32)
if free > 0 || locked > 0 {
fmt.Printf("%-5s %18f %10f\n", e.Asset, free, locked)
}
}
我们在 for 循环中遍历余额。可用金额是自由可用的,而锁定金额则被锁定在现有订单中。
Golang Binance 列出价格
要列出当前价格,我们调用 NewListPricesService 服务。
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"github.com/adshao/go-binance/v2"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
res, err := client.NewListPricesService().
Do(context.Background())
if err != nil {
log.Fatal(err)
}
for _, e := range res {
price, _ := strconv.ParseFloat(e.Price, 32)
fmt.Printf("%-14s %20f\n", e.Symbol, price)
}
}
该示例列出了所有交易对的价格。
$ go run main.go ETHBTC 0.065500 LTCBTC 0.003044 BNBBTC 0.011405 NEOBTC 0.000350 QTUMETH 0.001455 EOSETH 0.000541 SNTETH 0.000014 BNTETH 0.000250 ...
在下一个示例中,我们将检查特定交易对的当前价格。
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"github.com/adshao/go-binance/v2"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
res, err := client.NewListPricesService().Symbol("LTCUSDT").
Do(context.Background())
if err != nil {
log.Fatal(err)
}
for _, e := range res {
price, _ := strconv.ParseFloat(e.Price, 32)
fmt.Printf("%-14s %20f\n", e.Symbol, price)
}
}
使用 Symbol 函数,我们检查 LTCUSDT 交易对的价格。
最后,我们检查几个选定交易对的价格。
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"github.com/adshao/go-binance/v2"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
res, err := client.NewListPricesService().Symbols([]string{"LTCBUSD", "LTCUSDT", "LTCBTC", "LTCETH"}).
Do(context.Background())
if err != nil {
log.Fatal(err)
}
for _, e := range res {
price, _ := strconv.ParseFloat(e.Price, 32)
fmt.Printf("%-14s %20f\n", e.Symbol, price)
}
}
要列出几个交易对的价格,我们使用 Symbols 函数。
$ go run main.go LTCBTC 0.003042 LTCETH 0.046490 LTCUSDT 86.349998 LTCBUSD 86.370003
Golang Binance 列出订单
NewListOrdersService 用于列出已执行的订单。
package main
import (
"context"
"log"
"os"
"time"
"github.com/adshao/go-binance/v2"
"github.com/fatih/color"
"github.com/rodaine/table"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
orders, err := client.NewListOrdersService().Symbol("FTMBUSD").
Do(context.Background())
if err != nil {
log.Fatal(err)
}
tbl := table.New("Date", "Symbol", "Price", "Qty", "Side", "Type", "Status")
headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
columnFmt := color.New(color.FgBlue).SprintfFunc()
tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt)
for _, o := range orders {
t := time.UnixMilli(o.Time)
tf := t.Format("Jan 2, 2006")
tbl.AddRow(tf, o.Symbol, o.Price, o.ExecutedQuantity, string(o.Side),
string(o.Type), string(o.Status))
}
tbl.Print()
}
该程序列出了 FTMBUSD 的订单。数据以整洁的表格显示。表格使用 rodaine/table 包创建。颜色使用 fatih/color 包创建。
orders, err := client.NewListOrdersService().Symbol("FTMBUSD").
Do(context.Background())
我们为 FTMBUSD 交易对调用该服务。
tbl := table.New("Date", "Symbol", "Price", "Qty", "Side", "Type", "Status")
headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
columnFmt := color.New(color.FgBlue).SprintfFunc()
tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt)
我们设置表头列及其格式。
for _, o := range orders {
t := time.UnixMilli(o.Time)
tf := t.Format("Jan 2, 2006")
tbl.AddRow(tf, o.Symbol, o.Price, o.ExecutedQuantity, string(o.Side),
string(o.Type), string(o.Status))
}
我们遍历获取的订单并将它们添加到表中。
tbl.Print()
最后,表格被打印到控制台。
订单簿
订单簿是特定资产当前买入订单(bid)和卖出订单(ask)的列表。订单簿列出买入/卖出订单的价格以及买卖代币的数量。
买入价格显示为绿色数字,卖出价格显示为红色数字。
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/adshao/go-binance/v2"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
)
func main() {
var (
apiKey = os.Getenv("BINANCE_API_KEY")
secretKey = os.Getenv("BINANCE_SECRET_KEY")
)
client := binance.NewClient(apiKey, secretKey)
tickers, err := client.NewDepthService().Symbol("LTCBUSD").Limit(15).
Do(context.Background())
if err != nil {
log.Fatal(err)
}
// Bids
t := table.NewWriter()
t.SetTitle("LTC")
t.SetCaption("Bids")
t.SetAutoIndex(true)
t.SetStyle(table.StyleColoredGreenWhiteOnBlack)
t.Style().Format.Header = text.FormatTitle
t.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, Align: text.AlignRight},
{Number: 2, Align: text.AlignRight}})
t.AppendHeader(table.Row{"Price", "Quatity"})
for _, bid := range tickers.Bids {
t.AppendRow(table.Row{bid.Price, bid.Quantity})
}
fmt.Println(t.Render())
fmt.Println()
// Asks
t2 := table.NewWriter()
t2.SetTitle("LTC")
t2.SetCaption("Asks")
t2.SetAutoIndex(true)
t2.SetStyle(table.StyleColoredRedWhiteOnBlack)
t2.Style().Format.Header = text.FormatTitle
t2.Style().Format.Row = text.Format(text.AlignRight)
t2.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, Align: text.AlignRight},
{Number: 2, Align: text.AlignRight}})
t2.AppendHeader(table.Row{"Price", "Quatity"})
for _, ask := range tickers.Asks {
t2.AppendRow(table.Row{ask.Price, ask.Quantity})
}
fmt.Println(t2.Render())
}
该程序显示了 Binance 交易所 LTCBUSD 交易对的订单簿。买入显示在绿色表格中,卖出显示在红色表格中。我们使用 go-pretty 包创建表格。
tickers, err := client.NewDepthService().Symbol("LTCBUSD").Limit(15).
Do(context.Background())
订单簿通过 NewDepthService 检索。我们将行数限制为 15。
// Bids
t := table.NewWriter()
t.SetTitle("LTC")
t.SetCaption("Bids")
t.SetAutoIndex(true)
t.SetStyle(table.StyleColoredGreenWhiteOnBlack)
t.Style().Format.Header = text.FormatTitle
t.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, Align: text.AlignRight},
{Number: 2, Align: text.AlignRight}})
我们为买入/卖出订单设置表。
for _, bid := range tickers.Bids {
t.AppendRow(table.Row{bid.Price, bid.Quantity})
}
fmt.Println(t.Render())
我们用数据填充表并将其渲染到控制台。买入通过 Bids 字段访问。
来源
在本文中,我们已经在 Golang 中处理了 Binance 交易所。