binance

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 9, 2021 License: MIT Imports: 12 Imported by: 0

README

Binance API Go Language SDK

Go Report Card Build Status codecov license Go Version GoDoc Release Release Date Commit

This is a Binance Go language sdk that uses a method similar to HuobiRDCenter/huobi_Golang

Official Documents

Please make sure you have read the Binance API document before continuing.

Precautions

You are very welcome to submit issues or pull requests to share with this project to make the project more perfect

  • Remove all WAPI endpoints

    As Binance has planned to remove all WAPI endpoints from the Binance API at 2021-08-01 2:00 AM (UTC). So this the repo has removed all WAPI endpoints from the Binance API in advance More Information

  • spot/client/market.go:Line185 GetCandlestick()

    It is not recommended using this method, this method may have type errors, please use websocket subscription to obtain data.

List of implemented APIs

The following table shows the functions included in this SDK

Spot/Margin/Savings/Mining

Category Client Access Type
Common System Status (SAPI) RESTful API
Test Connectivity RESTful API
Check ServerTime RESTful API
Wallet All Coin's Information RESTful API
Daily Account Snapshot RESTful API
Disabled/Enabled Fast Withdraw RESTful API
Withdraw (SAPI) RESTful API
Deposit History(supporting network) RESTful API
Withdraw History(supporting network) RESTful API
Deposit Address(supporting network) RESTful API
Account Status (SAPI) RESTful API
Account API Trading Status (SAPI) RESTful API
DustLog (SAPI) RESTful API
Dust Transfer RESTful API
Asset Dividend Record RESTful API
Asset Detail (SAPI) RESTful API
Trade Fee (SAPI) RESTful API
User Universal Transfer RESTful API
Query User Universal Transfer History RESTful API
Market Order Book RESTful API
Recent Trades List RESTful API
Old Trade Lookup RESTful API
Aggregate Trade RESTful API
Candlestick RESTful API
Current Average Price RESTful API
24h Ticker Price Change RESTful API
Symbol Price Ticker RESTful API
Symbol Order Book Ticker RESTful API
Aggregate Trade WebSocket
Trade WebSocket
Candlestick WebSocket
Individual Symbol Mini Ticker WebSocket
All Market Mini Tickers WebSocket
Individual Symbol Ticker WebSocket
All Market Tickers WebSocket
Individual Symbol Book Ticker WebSocket
All Book Tickers WebSocket
Partial Book Depth WebSocket
Diff. Book Depth WebSocket
Trade Test New Order RESTful API
New order RESTful API
Cancel order RESTful API
Cancel all order RESTful API
Query order RESTful API
Current open orders RESTful API
All orders RESTful API
New OCO RESTful API
Cancel OCO RESTful API
Query OCO RESTful API
Query all OCO RESTful API
Query Open OCO RESTful API
Account Information RESTful API
Account Trade List RESTful API
Account Create Spot/Margin/Isolated Listen Key RESTful API
Ping/KeepAlive Spot/Margin/Isolated Listen Key RESTful API
Delete Spot/Margin/Isolated Listen Key RESTful PAI
Account Update WebSocket
Balance Update WebSocket
Order Update WebSocket

USDⓈ-M Futures

Category Client Access Type
Market Aggregate Trade WebSocket
Market Price WebSocket
All Market Price WebSocket
Kline/Candlestick WebSocket
Continuous Candlestick WebSocket
Individual Symbol Mini Ticker WebSocket
All Market Mini Tickers WebSocket
Individual Symbol Ticker WebSocket
All Book Tickers WebSocket
Liquidation Order WebSocket
All Market Liquidation Orders WebSocket
Partial Book Depth WebSocket
Diff. Book Depth WebSocket
BLVT Info WebSocket
BLVT NAV Kline/Candlestick WebSocket
Composite Index Symbol WebSocket

Usage

Below are some examples of usage

RESTful wallet transfer

Examples of user transfers in the universal

package spotclient

import (
	binance "github.com/dirname/binance"
	"github.com/dirname/binance/config"
	"github.com/shopspring/decimal"
	"reflect"
	"testing"
	"time"
)

func init() {
	logger.Enable(false)
	walletClient = spotclient.NewWalletClient(config.SpotRestHost, config.AppKey, config.AppSecret)
}

func universalTransfer() {
	response, err := walletClient.UniversalTransfer("UMFUTURE_MAIN", "USDT", "10", 0)
	if err != nil {
		logger.Error("universalTransfer err: %s", err.Error())
	}
	switch response.(type) {
	case model.APIErrorResponse:
		logger.Info("universalTransfer API error: %v", response.(model.APIErrorResponse))
	case spotclient.UniversalTransferResponse:
		logger.Info("universalTransfer: %v", response.(spotclient.UniversalTransferResponse))
	default:
		logger.Info("universalTransfer Unknown response: %v", response)
	}
}

WebSocket market quotes

Take the Kline of the USDⓈ-M Futures as an example

package main

import (
	"fmt"
	"github.com/dirname/binance/futures/usdt/websocket/market"
	logger "github.com/dirname/binance/logging"
	"github.com/dirname/binance/model"
	"time"
)

func main() {
	client := futuresusdt.NewUSDFuturesCandlestickWebsocketClient("btcusdt@kline_1m")
	client.SetReadTimerInterval(5 * time.Second)
	client.SetReconnectWaitTime(5 * time.Second)
	client.SetKeepAliveInterval(2 * time.Minute)
	client.SetHandler(func() {
		client.Subscribe(123, "btcusdt@kline_1m", "btcusdt@kline_5m")
		client.SetCombined(true, 123)
	}, func(response interface{}) {
		switch response.(type) {
		case futuresusdt.CandlestickResponse:
			logger.Info("Candlestick Response: %v", response.(futuresusdt.CandlestickResponse))
		case futuresusdt.CandlestickCombinedResponse:
			logger.Info("CandlestickCombinedResponse: %v", response.(futuresusdt.CandlestickCombinedResponse))
		case model.WebsocketCommonResponse:
			logger.Info("Websocket Response: %v", response.(model.WebsocketCommonResponse))
		case model.WebsocketErrorResponse:
			logger.Info("Websocket Error Response: %v", response.(model.WebsocketErrorResponse))
		default:
			logger.Info("Unknown Response: %v", response)
		}
	})
	client.Connect(true)
	fmt.Scanln()

	client.Unsubscribe(123, "btcusdt@kline_1m", "btcusdt@kline_5m")
	client.Close()
	logger.Info("Client closed")
}

Disclaimer

This SDK is for personal use and has not been officially produced. They are only used to help users become familiar with API endpoint. Please use it with caution, and expand the R&D according to your own situation.

In addition, the performance and stability of this sdk need to be tested by yourself, and the loss due to performance or stability shall be borne by you

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HttpRequest

func HttpRequest(request *http.Request) ([]byte, error)

HttpRequest send a http request

Types

type ConnectedHandler

type ConnectedHandler func()

ConnectedHandler invoked after websocket connected

type MessageHandler

type MessageHandler func(message []byte) (interface{}, error)

MessageHandler invoked after valid message received

type PingHandler

type PingHandler func(appData string) error

PingHandler invoked after ws received ping frame

type PongHandler

type PongHandler func(appData string) error

PongHandler invoked after ws received pong frame

type PrivateUrlBuilder

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

PrivateUrlBuilder build private url

func NewPrivateUrlBuilder

func NewPrivateUrlBuilder(host, appKey, appSecret string) *PrivateUrlBuilder

NewPrivateUrlBuilder factory function

func (*PrivateUrlBuilder) Build

func (p *PrivateUrlBuilder) Build(method, path, params string, sign bool, timeStamp bool, recv time.Duration) (*http.Request, error)

Build build a private url

func (*PrivateUrlBuilder) SetAPIKey

func (p *PrivateUrlBuilder) SetAPIKey(appKey, appSecret string)

SetAPIKey set API information

type PublicUrlBuilder

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

PublicUrlBuilder build public url

func NewPublicUrlBuilder

func NewPublicUrlBuilder(host string) *PublicUrlBuilder

NewPublicUrlBuilder factory function

func (*PublicUrlBuilder) Build

func (p *PublicUrlBuilder) Build(method, path, params string) (*http.Request, error)

Build build a public url

type ResponseHandler

type ResponseHandler func(response interface{})

ResponseHandler invoked after response is parsed

type Signer

type Signer struct {
	Key []byte
}

Signer calculating signature

func (*Signer) Sum

func (s *Signer) Sum(queryString string) string

Sum Generation signature

type WebsocketClient

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

WebsocketClient websocket client class that get data from websocket

func (*WebsocketClient) Close

func (w *WebsocketClient) Close()

Close close the connection to server

func (*WebsocketClient) Connect

func (w *WebsocketClient) Connect(autoReconnect bool)

Connect connect to websocket server

func (*WebsocketClient) Init

func (w *WebsocketClient) Init(host string, stream ...string)

Init Initializer websocket client

func (*WebsocketClient) Send

func (w *WebsocketClient) Send(data string)

Send send the message to ws client

func (*WebsocketClient) SendJSON

func (w *WebsocketClient) SendJSON(data interface{})

SendJSON send the json to ws client

func (*WebsocketClient) SetConnectedHandler

func (w *WebsocketClient) SetConnectedHandler(handler ConnectedHandler)

SetConnectedHandler set client connected handler

func (*WebsocketClient) SetKeepAliveInterval

func (w *WebsocketClient) SetKeepAliveInterval(time time.Duration)

SetKeepAliveInterval set time to keep alive

func (*WebsocketClient) SetMessageHandler

func (w *WebsocketClient) SetMessageHandler(handler MessageHandler)

SetMessageHandler set client on message handler

func (*WebsocketClient) SetPingHandler

func (w *WebsocketClient) SetPingHandler(handler PingHandler)

SetPingHandler set client on ping handler

func (*WebsocketClient) SetPongHandler

func (w *WebsocketClient) SetPongHandler(handler PongHandler)

SetPongHandler set client on pong handler

func (*WebsocketClient) SetReadTimerInterval

func (w *WebsocketClient) SetReadTimerInterval(time time.Duration)

SetReadTimerInterval set time wait ws to received

func (*WebsocketClient) SetReconnectWaitTime

func (w *WebsocketClient) SetReconnectWaitTime(time time.Duration)

SetReconnectWaitTime set time wait ws reconnect

func (*WebsocketClient) SetResponseHandler

func (w *WebsocketClient) SetResponseHandler(handler ResponseHandler)

SetResponseHandler set client on response handler

Jump to

Keyboard shortcuts

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