bbgo_origin/pkg/exchange/binance/exchange.go

550 lines
14 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
"time"
2020-07-11 05:02:53 +00:00
"github.com/adshao/go-binance"
"github.com/google/uuid"
"github.com/pkg/errors"
2020-07-11 07:19:36 +00:00
2020-08-13 02:11:27 +00:00
"github.com/sirupsen/logrus"
2020-11-10 06:19:33 +00:00
"github.com/c9s/bbgo/pkg/fixedpoint"
2020-10-11 08:46:15 +00:00
"github.com/c9s/bbgo/pkg/types"
"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,
}
}
func (e *Exchange) Name() types.ExchangeName {
return types.ExchangeBinance
}
2020-10-14 02:16:59 +00:00
func (e *Exchange) QueryMarkets(ctx context.Context) (types.MarketMap, error) {
2020-10-16 02:14:36 +00:00
log.Info("querying market info...")
2020-10-14 02:16:59 +00:00
exchangeInfo, err := e.Client.NewExchangeInfoService().Do(ctx)
if err != nil {
return nil, err
}
markets := types.MarketMap{}
for _, symbol := range exchangeInfo.Symbols {
market := types.Market{
Symbol: symbol.Symbol,
PricePrecision: symbol.QuotePrecision,
VolumePrecision: symbol.BaseAssetPrecision,
QuoteCurrency: symbol.QuoteAsset,
BaseCurrency: symbol.BaseAsset,
}
if f := symbol.MinNotionalFilter(); f != nil {
2020-10-14 02:16:59 +00:00
market.MinNotional = util.MustParseFloat(f.MinNotional)
2020-10-14 02:39:14 +00:00
market.MinAmount = util.MustParseFloat(f.MinNotional)
2020-10-14 02:16:59 +00:00
}
// The LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for a symbol.
// There are 3 parts:
// minQty defines the minimum quantity/icebergQty allowed.
// maxQty defines the maximum quantity/icebergQty allowed.
// stepSize defines the intervals that a quantity/icebergQty can be increased/decreased by.
if f := symbol.LotSizeFilter(); f != nil {
2020-10-14 02:16:59 +00:00
market.MinLot = util.MustParseFloat(f.MinQuantity)
market.MinQuantity = util.MustParseFloat(f.MinQuantity)
market.MaxQuantity = util.MustParseFloat(f.MaxQuantity)
// market.StepSize = util.MustParseFloat(f.StepSize)
}
if f := symbol.PriceFilter(); f != nil {
market.MaxPrice = util.MustParseFloat(f.MaxPrice)
market.MinPrice = util.MustParseFloat(f.MinPrice)
market.TickSize = util.MustParseFloat(f.TickSize)
2020-10-14 02:16:59 +00:00
}
markets[symbol.Symbol] = market
}
return markets, nil
}
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
}
2020-10-03 12:09:22 +00:00
func (e *Exchange) NewStream() types.Stream {
return NewStream(e.Client)
2020-07-11 05:02:53 +00:00
}
func (e *Exchange) QueryWithdrawHistory(ctx context.Context, asset string, since, until time.Time) (allWithdraws []types.Withdraw, err error) {
2020-08-13 02:11:27 +00:00
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
}
2020-10-12 09:15:33 +00:00
req := e.Client.NewListWithdrawsService()
if len(asset) > 0 {
req.Asset(asset)
}
withdraws, err := req.
2020-08-13 02:11:27 +00:00
StartTime(startTime.UnixNano() / int64(time.Millisecond)).
EndTime(endTime.UnixNano() / int64(time.Millisecond)).
Do(ctx)
if err != nil {
return allWithdraws, err
2020-08-13 02:11:27 +00:00
}
for _, d := range withdraws {
if _, ok := txIDs[d.TxID]; ok {
continue
}
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"
default:
status = fmt.Sprintf("unsupported code: %d", d.Status)
2020-08-13 02:11:27 +00:00
}
txIDs[d.TxID] = struct{}{}
allWithdraws = append(allWithdraws, types.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
}
func (e *Exchange) QueryDepositHistory(ctx context.Context, asset string, since, until time.Time) (allDeposits []types.Deposit, err error) {
2020-08-13 02:11:27 +00:00
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
}
2020-10-12 09:15:33 +00:00
req := e.Client.NewListDepositsService()
if len(asset) > 0 {
req.Asset(asset)
}
deposits, err := req.
2020-08-13 02:11:27 +00:00
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 := types.DepositStatus(fmt.Sprintf("code: %d", d.Status))
2020-08-13 02:11:27 +00:00
switch d.Status {
case 0:
status = types.DepositPending
2020-08-13 02:11:27 +00:00
case 6:
// https://www.binance.com/en/support/faq/115003736451
status = types.DepositCredited
2020-08-13 02:11:27 +00:00
case 1:
status = types.DepositSuccess
2020-08-13 02:11:27 +00:00
}
txIDs[d.TxID] = struct{}{}
allDeposits = append(allDeposits, types.Deposit{
2020-08-13 02:11:27 +00:00
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-10-06 09:32:41 +00:00
func (e *Exchange) QueryAccountBalances(ctx context.Context) (types.BalanceMap, error) {
2020-07-13 04:28:40 +00:00
account, err := e.QueryAccount(ctx)
if err != nil {
return nil, err
}
2020-10-18 03:30:37 +00:00
return account.Balances(), nil
2020-07-13 04:28:40 +00:00
}
// 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,
2020-11-10 06:19:33 +00:00
Available: fixedpoint.Must(fixedpoint.NewFromString(b.Free)),
Locked: fixedpoint.Must(fixedpoint.NewFromString(b.Locked)),
2020-07-13 04:28:40 +00:00
}
}
2020-10-18 03:30:37 +00:00
a := &types.Account{
2020-11-06 19:18:05 +00:00
MakerCommission: int(account.MakerCommission),
TakerCommission: int(account.TakerCommission),
2020-10-18 03:30:37 +00:00
}
a.UpdateBalances(balances)
return a, nil
2020-07-13 04:28:40 +00:00
}
func (e *Exchange) QueryOpenOrders(ctx context.Context, symbol string) (orders []types.Order, err error) {
2020-11-05 00:33:57 +00:00
binanceOrders, err := e.Client.NewListOpenOrdersService().Symbol(symbol).Do(ctx)
if err != nil {
return orders, err
}
2020-11-05 00:33:57 +00:00
for _, binanceOrder := range binanceOrders {
2020-12-02 14:44:57 +00:00
order, err := ToGlobalOrder(binanceOrder)
if err != nil {
return orders, err
}
orders = append(orders, *order)
}
return orders, err
}
func (e *Exchange) QueryClosedOrders(ctx context.Context, symbol string, since, until time.Time, lastOrderID uint64) (orders []types.Order, err error) {
if until.Sub(since) >= 24*time.Hour {
until = since.Add(24*time.Hour - time.Millisecond)
}
2020-11-05 00:33:57 +00:00
time.Sleep(3 * time.Second)
2020-11-05 00:33:57 +00:00
log.Infof("querying closed orders %s from %s <=> %s ...", symbol, since, until)
req := e.Client.NewListOrdersService().
Symbol(symbol)
2020-11-05 00:33:57 +00:00
if lastOrderID > 0 {
req.OrderID(int64(lastOrderID))
} else {
req.StartTime(since.UnixNano() / int64(time.Millisecond)).
EndTime(until.UnixNano() / int64(time.Millisecond))
}
2020-11-05 00:33:57 +00:00
binanceOrders, err := req.Do(ctx)
if err != nil {
return orders, err
}
2020-11-05 00:33:57 +00:00
if len(binanceOrders) == 0 {
return orders, nil
}
2020-11-05 00:33:57 +00:00
for _, binanceOrder := range binanceOrders {
2020-12-02 14:44:57 +00:00
order, err := ToGlobalOrder(binanceOrder)
if err != nil {
return orders, err
2020-11-05 00:33:57 +00:00
}
orders = append(orders, *order)
2020-11-05 00:33:57 +00:00
}
return orders, nil
2020-11-05 00:33:57 +00:00
}
func (e *Exchange) CancelOrders(ctx context.Context, orders ...types.Order) (err2 error) {
for _, o := range orders {
var req = e.Client.NewCancelOrderService()
// Mandatory
req.Symbol(o.Symbol)
if o.OrderID > 0 {
req.OrderID(int64(o.OrderID))
} else if len(o.ClientOrderID) > 0 {
req.NewClientOrderID(o.ClientOrderID)
}
_, err := req.Do(ctx)
if err != nil {
log.WithError(err).Errorf("order cancel error")
err2 = err
}
}
return err2
}
func (e *Exchange) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error) {
for _, order := range orders {
orderType, err := toLocalOrderType(order.Type)
if err != nil {
return createdOrders, err
}
2020-07-11 05:02:53 +00:00
clientOrderID := uuid.New().String()
if len(order.ClientOrderID) > 0 {
clientOrderID = order.ClientOrderID
}
req := e.Client.NewCreateOrderService().
Symbol(order.Symbol).
Side(binance.SideType(order.Side)).
NewClientOrderID(clientOrderID).
Type(orderType)
2020-07-11 07:27:26 +00:00
req.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
2020-12-03 01:25:47 +00:00
switch order.Type {
case types.OrderTypeStopLimit, types.OrderTypeStopMarket:
if len(order.StopPriceString) == 0 {
return createdOrders, fmt.Errorf("stop price string can not be empty")
}
req.StopPrice(order.StopPriceString)
}
if len(order.TimeInForce) > 0 {
// TODO: check the TimeInForce value
req.TimeInForce(binance.TimeInForceType(order.TimeInForce))
}
2020-07-11 05:02:53 +00:00
response, err := req.Do(ctx)
if err != nil {
return createdOrders, err
}
2020-07-11 07:27:26 +00:00
log.Infof("order creation response: %+v", response)
retOrder := binance.Order{
Symbol: response.Symbol,
OrderID: response.OrderID,
ClientOrderID: response.ClientOrderID,
Price: response.Price,
OrigQuantity: response.OrigQuantity,
ExecutedQuantity: response.ExecutedQuantity,
CummulativeQuoteQuantity: response.CummulativeQuoteQuantity,
Status: response.Status,
TimeInForce: response.TimeInForce,
Type: response.Type,
Side: response.Side,
// StopPrice:
// IcebergQuantity:
Time: response.TransactTime,
// UpdateTime:
// IsWorking: ,
}
2020-12-02 14:44:57 +00:00
createdOrder, err := ToGlobalOrder(&retOrder)
if err != nil {
return createdOrders, err
}
if createdOrder == nil {
return createdOrders, errors.New("nil converted order")
}
createdOrders = append(createdOrders, *createdOrder)
2020-07-11 07:27:26 +00:00
}
return createdOrders, err
2020-07-11 07:27:26 +00:00
}
2020-11-06 16:49:17 +00:00
// QueryKLines queries the Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
func (e *Exchange) QueryKLines(ctx context.Context, symbol string, interval types.Interval, options types.KLineQueryOptions) ([]types.KLine, error) {
2020-10-10 04:02:06 +00:00
2020-07-15 04:20:44 +00:00
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-10-10 04:02:06 +00:00
// avoid rate limit
2020-11-06 16:49:17 +00:00
time.Sleep(500 * time.Millisecond)
2020-10-06 09:32:41 +00:00
req := e.Client.NewKlinesService().
Symbol(symbol).
Interval(string(interval)).
2020-07-15 04:20:44 +00:00
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{
Exchange: "binance",
2020-07-11 05:02:53 +00:00
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,
2020-11-06 16:49:17 +00:00
NumberOfTrades: uint64(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 {
2020-10-06 10:44:56 +00:00
req.Limit(int(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-12-02 14:44:57 +00:00
localTrade, err := ToGlobalTrade(*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
}
func (e *Exchange) BatchQueryKLines(ctx context.Context, symbol string, interval types.Interval, startTime, endTime time.Time) ([]types.KLine, error) {
2020-08-14 05:08:09 +00:00
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
}