bbgo_origin/bbgo/exchange/binance/exchange.go

512 lines
12 KiB
Go
Raw Normal View History

2020-07-11 05:02:53 +00:00
package binance
import (
"context"
2020-07-11 07:27:26 +00:00
"fmt"
2020-07-11 07:19:36 +00:00
"strconv"
"time"
2020-07-11 05:02:53 +00:00
"github.com/adshao/go-binance"
2020-07-11 07:19:36 +00:00
2020-08-13 02:11:27 +00:00
"github.com/sirupsen/logrus"
2020-07-11 07:18:31 +00:00
"github.com/c9s/bbgo/pkg/bbgo/types"
2020-07-11 05:08:50 +00:00
"github.com/c9s/bbgo/pkg/util"
2020-07-11 05:02:53 +00:00
)
2020-08-11 00:36:36 +00:00
var log = logrus.WithFields(logrus.Fields{
"exchange": "binance",
})
func init() {
_ = types.Exchange(&Exchange{})
}
2020-07-11 05:02:53 +00:00
type Exchange struct {
Client *binance.Client
}
func New(key, secret string) *Exchange {
2020-07-11 05:08:50 +00:00
var client = binance.NewClient(key, secret)
return &Exchange{
Client: client,
}
}
2020-07-11 05:02:53 +00:00
func (e *Exchange) QueryAveragePrice(ctx context.Context, symbol string) (float64, error) {
resp, err := e.Client.NewAveragePriceService().Symbol(symbol).Do(ctx)
if err != nil {
return 0, err
}
2020-07-11 05:08:50 +00:00
return util.MustParseFloat(resp.Price), nil
2020-07-11 05:02:53 +00:00
}
func (e *Exchange) NewPrivateStream() (types.PrivateStream, error) {
return NewPrivateStream(e.Client)
}
2020-10-03 10:35:28 +00:00
func NewPrivateStream(client *binance.Client) (*Stream, error) {
// binance BalanceUpdate = withdrawal or deposit changes
/*
stream.OnBalanceUpdateEvent(func(e *binance.BalanceUpdateEvent) {
a.mu.Lock()
defer a.mu.Unlock()
delta := util.MustParseFloat(e.Delta)
if balance, ok := a.Balances[e.Asset]; ok {
balance.Available += delta
a.Balances[e.Asset] = balance
}
})
*/
2020-10-03 10:35:28 +00:00
return &Stream{
Client: client,
2020-07-11 05:02:53 +00:00
}, nil
}
2020-08-13 02:11:27 +00:00
type Withdraw struct {
ID string `json:"id"`
Asset string `json:"asset"`
Amount float64 `json:"amount"`
Address string `json:"address"`
AddressTag string `json:"addressTag"`
2020-08-31 04:32:51 +00:00
Status string `json:"status"`
2020-08-13 02:11:27 +00:00
TransactionID string `json:"txId"`
TransactionFee float64 `json:"transactionFee"`
WithdrawOrderID string `json:"withdrawOrderId"`
ApplyTime time.Time `json:"applyTime"`
Network string `json:"network"`
}
func (e *Exchange) QueryWithdrawHistory(ctx context.Context, asset string, since, until time.Time) (allWithdraws []Withdraw, err error) {
startTime := since
txIDs := map[string]struct{}{}
for startTime.Before(until) {
// startTime ~ endTime must be in 90 days
endTime := startTime.AddDate(0, 0, 60)
if endTime.After(until) {
endTime = until
}
withdraws, err := e.Client.NewListWithdrawsService().
Asset(asset).
StartTime(startTime.UnixNano() / int64(time.Millisecond)).
EndTime(endTime.UnixNano() / int64(time.Millisecond)).
Do(ctx)
if err != nil {
return nil, err
}
for _, d := range withdraws {
if _, ok := txIDs[d.TxID]; ok {
continue
}
// 0(0:pending,6: credited but cannot withdraw, 1:success)
status := ""
switch d.Status {
case 0:
status = "email_sent"
case 1:
status = "cancelled"
case 2:
status = "awaiting_approval"
case 3:
status = "rejected"
case 4:
status = "processing"
case 5:
status = "failure"
case 6:
status = "completed"
}
txIDs[d.TxID] = struct{}{}
allWithdraws = append(allWithdraws, Withdraw{
2020-08-31 04:32:51 +00:00
ApplyTime: time.Unix(0, d.ApplyTime*int64(time.Millisecond)),
Asset: d.Asset,
Amount: d.Amount,
Address: d.Address,
AddressTag: d.AddressTag,
TransactionID: d.TxID,
TransactionFee: d.TransactionFee,
2020-08-13 02:11:27 +00:00
WithdrawOrderID: d.WithdrawOrderID,
2020-08-31 04:32:51 +00:00
Network: d.Network,
Status: status,
2020-08-13 02:11:27 +00:00
})
}
startTime = endTime
}
return allWithdraws, nil
}
type Deposit struct {
Time time.Time `json:"time"`
Amount float64 `json:"amount"`
Asset string `json:"asset"`
Address string `json:"address"`
AddressTag string `json:"addressTag"`
TransactionID string `json:"txId"`
Status string `json:"status"`
}
func (e *Exchange) QueryDepositHistory(ctx context.Context, asset string, since, until time.Time) (allDeposits []Deposit, err error) {
startTime := since
txIDs := map[string]struct{}{}
for startTime.Before(until) {
// startTime ~ endTime must be in 90 days
endTime := startTime.AddDate(0, 0, 60)
if endTime.After(until) {
endTime = until
}
deposits, err := e.Client.NewListDepositsService().
Asset(asset).
StartTime(startTime.UnixNano() / int64(time.Millisecond)).
EndTime(endTime.UnixNano() / int64(time.Millisecond)).
Do(ctx)
if err != nil {
return nil, err
}
for _, d := range deposits {
if _, ok := txIDs[d.TxID]; ok {
continue
}
// 0(0:pending,6: credited but cannot withdraw, 1:success)
status := ""
switch d.Status {
case 0:
status = "pending"
case 6:
status = "credited"
case 1:
status = "success"
}
txIDs[d.TxID] = struct{}{}
allDeposits = append(allDeposits, Deposit{
Time: time.Unix(0, d.InsertTime*int64(time.Millisecond)),
Asset: d.Asset,
Amount: d.Amount,
Address: d.Address,
AddressTag: d.AddressTag,
TransactionID: d.TxID,
Status: status,
})
}
startTime = endTime
}
return allDeposits, nil
}
2020-07-13 04:28:40 +00:00
func (e *Exchange) QueryAccountBalances(ctx context.Context) (map[string]types.Balance, error) {
account, err := e.QueryAccount(ctx)
if err != nil {
return nil, err
}
return account.Balances, nil
}
// PlatformFeeCurrency
func (e *Exchange) PlatformFeeCurrency() string {
2020-08-03 12:06:33 +00:00
return "BNB"
}
2020-07-13 04:28:40 +00:00
func (e *Exchange) QueryAccount(ctx context.Context) (*types.Account, error) {
account, err := e.Client.NewGetAccountService().Do(ctx)
if err != nil {
return nil, err
}
var balances = map[string]types.Balance{}
2020-07-15 04:20:44 +00:00
for _, b := range account.Balances {
2020-07-13 04:28:40 +00:00
balances[b.Asset] = types.Balance{
Currency: b.Asset,
Available: util.MustParseFloat(b.Free),
Locked: util.MustParseFloat(b.Locked),
}
}
return &types.Account{
MakerCommission: account.MakerCommission,
TakerCommission: account.TakerCommission,
Balances: balances,
}, nil
}
2020-08-14 05:11:34 +00:00
func (e *Exchange) SubmitOrder(ctx context.Context, order *types.SubmitOrder) error {
2020-07-11 05:02:53 +00:00
/*
limit order example
order, err := Client.NewCreateOrderService().
Symbol(Symbol).
Side(side).
Type(binance.OrderTypeLimit).
TimeInForce(binance.TimeInForceTypeGTC).
Quantity(volumeString).
Price(priceString).
Do(ctx)
*/
2020-07-11 07:27:26 +00:00
orderType, err := toLocalOrderType(order.Type)
if err != nil {
return err
}
2020-07-11 05:02:53 +00:00
req := e.Client.NewCreateOrderService().
Symbol(order.Symbol).
2020-07-11 07:18:31 +00:00
Side(binance.SideType(order.Side)).
2020-07-11 07:27:26 +00:00
Type(orderType).
Quantity(order.QuantityString)
2020-07-11 05:02:53 +00:00
if len(order.PriceString) > 0 {
req.Price(order.PriceString)
2020-07-11 05:02:53 +00:00
}
if len(order.TimeInForce) > 0 {
req.TimeInForce(order.TimeInForce)
}
retOrder, err := req.Do(ctx)
2020-08-11 00:36:36 +00:00
log.Infof("order created: %+v", retOrder)
2020-07-11 05:02:53 +00:00
return err
}
2020-07-11 07:27:26 +00:00
func toLocalOrderType(orderType types.OrderType) (binance.OrderType, error) {
switch orderType {
case types.OrderTypeLimit:
return binance.OrderTypeLimit, nil
case types.OrderTypeMarket:
return binance.OrderTypeMarket, nil
}
return "", fmt.Errorf("order type %s not supported", orderType)
}
2020-07-15 04:20:44 +00:00
func (e *Exchange) QueryKLines(ctx context.Context, symbol, interval string, options types.KLineQueryOptions) ([]types.KLine, error) {
var limit = 500
if options.Limit > 0 {
2020-07-11 12:40:19 +00:00
// default limit == 500
2020-07-15 04:20:44 +00:00
limit = options.Limit
2020-07-11 12:40:19 +00:00
}
2020-08-11 00:36:36 +00:00
log.Infof("querying kline %s %s %v", symbol, interval, options)
2020-07-11 05:02:53 +00:00
2020-07-15 04:20:44 +00:00
req := e.Client.NewKlinesService().Symbol(symbol).
Interval(interval).
Limit(limit)
if options.StartTime != nil {
req.StartTime(options.StartTime.UnixNano() / int64(time.Millisecond))
}
if options.EndTime != nil {
req.EndTime(options.EndTime.UnixNano() / int64(time.Millisecond))
}
resp, err := req.Do(ctx)
2020-07-11 05:02:53 +00:00
if err != nil {
return nil, err
}
var kLines []types.KLine
for _, k := range resp {
2020-07-11 05:02:53 +00:00
kLines = append(kLines, types.KLine{
Symbol: symbol,
Interval: interval,
StartTime: time.Unix(0, k.OpenTime*int64(time.Millisecond)),
EndTime: time.Unix(0, k.CloseTime*int64(time.Millisecond)),
Open: util.MustParseFloat(k.Open),
Close: util.MustParseFloat(k.Close),
High: util.MustParseFloat(k.High),
Low: util.MustParseFloat(k.Low),
Volume: util.MustParseFloat(k.Volume),
QuoteVolume: util.MustParseFloat(k.QuoteAssetVolume),
LastTradeID: 0,
NumberOfTrades: k.TradeNum,
Closed: true,
2020-07-11 05:02:53 +00:00
})
}
return kLines, nil
}
2020-09-18 10:15:45 +00:00
func (e *Exchange) QueryTrades(ctx context.Context, symbol string, options *types.TradeQueryOptions) (trades []types.Trade, err error) {
req := e.Client.NewListTradesService().
Limit(1000).
Symbol(symbol)
if options.Limit > 0 {
req.Limit(options.Limit)
}
if options.StartTime != nil {
req.StartTime(options.StartTime.UnixNano() / int64(time.Millisecond))
}
if options.EndTime != nil {
req.EndTime(options.EndTime.UnixNano() / int64(time.Millisecond))
}
if options.LastTradeID > 0 {
req.FromID(options.LastTradeID)
}
remoteTrades, err := req.Do(ctx)
if err != nil {
return nil, err
}
for _, t := range remoteTrades {
2020-07-26 16:54:49 +00:00
localTrade, err := convertRemoteTrade(*t)
if err != nil {
2020-08-11 00:36:36 +00:00
log.WithError(err).Errorf("can not convert binance trade: %+v", t)
2020-07-26 16:54:49 +00:00
continue
}
2020-08-11 00:36:36 +00:00
log.Infof("trade: %d %s % 4s price: % 13s volume: % 11s %6s % 5s %s", t.ID, t.Symbol, localTrade.Side, t.Price, t.Quantity, BuyerOrSellerLabel(t), MakerOrTakerLabel(t), localTrade.Time)
2020-07-26 16:54:49 +00:00
trades = append(trades, *localTrade)
}
2020-07-26 16:54:49 +00:00
return trades, nil
}
2020-09-18 10:15:45 +00:00
func (e *Exchange) BatchQueryTrades(ctx context.Context, symbol string, options *types.TradeQueryOptions) (allTrades []types.Trade, err error) {
var startTime = time.Now().Add(-7 * 24 * time.Hour)
if options.StartTime != nil {
startTime = *options.StartTime
}
2020-08-11 00:36:36 +00:00
log.Infof("querying %s trades from %s", symbol, startTime)
2020-07-11 05:02:53 +00:00
2020-08-03 08:42:33 +00:00
var lastTradeID = options.LastTradeID
2020-07-11 05:02:53 +00:00
for {
2020-09-18 10:15:45 +00:00
trades, err := e.QueryTrades(ctx, symbol, &types.TradeQueryOptions{
2020-08-03 07:25:06 +00:00
StartTime: &startTime,
Limit: options.Limit,
LastTradeID: lastTradeID,
2020-07-26 16:54:49 +00:00
})
2020-07-11 05:02:53 +00:00
if err != nil {
return allTrades, err
2020-07-11 05:02:53 +00:00
}
2020-08-03 08:42:33 +00:00
if len(trades) == 1 && trades[0].ID == lastTradeID {
2020-07-11 05:02:53 +00:00
break
}
for _, t := range trades {
2020-08-03 08:42:33 +00:00
// ignore the first trade if last TradeID is given
2020-07-11 05:02:53 +00:00
if t.ID == lastTradeID {
continue
}
allTrades = append(allTrades, t)
2020-07-11 05:02:53 +00:00
lastTradeID = t.ID
}
}
return allTrades, nil
2020-07-11 05:02:53 +00:00
}
func convertRemoteTrade(t binance.TradeV3) (*types.Trade, error) {
// skip trade ID that is the same. however this should not happen
var side string
if t.IsBuyer {
side = "BUY"
} else {
side = "SELL"
}
// trade time
mts := time.Unix(0, t.Time*int64(time.Millisecond))
price, err := strconv.ParseFloat(t.Price, 64)
if err != nil {
return nil, err
}
quantity, err := strconv.ParseFloat(t.Quantity, 64)
if err != nil {
return nil, err
}
quoteQuantity, err := strconv.ParseFloat(t.QuoteQuantity, 64)
if err != nil {
return nil, err
}
fee, err := strconv.ParseFloat(t.Commission, 64)
if err != nil {
return nil, err
}
return &types.Trade{
ID: t.ID,
Price: price,
2020-08-03 07:25:06 +00:00
Symbol: t.Symbol,
Exchange: "binance",
Quantity: quantity,
Side: side,
IsBuyer: t.IsBuyer,
IsMaker: t.IsMaker,
Fee: fee,
FeeCurrency: t.CommissionAsset,
QuoteQuantity: quoteQuantity,
Time: mts,
}, nil
}
2020-08-14 05:08:09 +00:00
func (e *Exchange) BatchQueryKLines(ctx context.Context, symbol, interval string, startTime, endTime time.Time) ([]types.KLine, error) {
var allKLines []types.KLine
for startTime.Before(endTime) {
klines, err := e.QueryKLines(ctx, symbol, interval, types.KLineQueryOptions{
StartTime: &startTime,
Limit: 1000,
})
if err != nil {
return nil, err
}
for _, kline := range klines {
if kline.EndTime.After(endTime) {
2020-08-14 05:08:09 +00:00
return allKLines, nil
}
allKLines = append(allKLines, kline)
startTime = kline.EndTime
2020-08-14 05:08:09 +00:00
}
// avoid rate limit
time.Sleep(100 * time.Millisecond)
}
return allKLines, nil
2020-08-14 05:47:55 +00:00
}
func (e *Exchange) BatchQueryKLineWindows(ctx context.Context, symbol string, intervals []string, startTime, endTime time.Time) (map[string]types.KLineWindow, error) {
klineWindows := map[string]types.KLineWindow{}
for _, interval := range intervals {
klines, err := e.BatchQueryKLines(ctx, symbol, interval, startTime, endTime)
if err != nil {
return klineWindows, err
}
klineWindows[interval] = klines
}
2020-08-14 05:08:09 +00:00
2020-08-14 05:47:55 +00:00
return klineWindows, nil
2020-08-14 05:08:09 +00:00
}