bbgo_origin/pkg/strategy/grid/strategy.go

363 lines
11 KiB
Go
Raw Normal View History

package grid
import (
"context"
2020-12-31 05:54:32 +00:00
"fmt"
"hash/fnv"
2020-11-12 06:50:08 +00:00
"sync"
2020-10-29 13:10:13 +00:00
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
2021-02-16 08:30:01 +00:00
"github.com/c9s/bbgo/pkg/service"
"github.com/c9s/bbgo/pkg/types"
)
2021-02-03 01:08:05 +00:00
const ID = "grid"
var log = logrus.WithField("strategy", ID)
2020-10-29 13:10:13 +00:00
func init() {
// Register the pointer of the strategy struct,
// so that bbgo knows what struct to be used to unmarshal the configs (YAML or JSON)
// Note: built-in strategies need to imported manually in the bbgo cmd package.
2021-02-03 01:08:05 +00:00
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
// The notification system will be injected into the strategy automatically.
// This field will be injected automatically since it's a single exchange strategy.
2021-02-02 18:26:41 +00:00
*bbgo.Notifiability `json:"-" yaml:"-"`
2021-02-02 18:26:41 +00:00
*bbgo.Graceful `json:"-" yaml:"-"`
2020-11-12 06:50:08 +00:00
// OrderExecutor is an interface for submitting order.
// This field will be injected automatically since it's a single exchange strategy.
2021-02-02 18:26:41 +00:00
bbgo.OrderExecutor `json:"-" yaml:"-"`
// Market stores the configuration of the market, for example, VolumePrecision, PricePrecision, MinLotSize... etc
// This field will be injected automatically since we defined the Symbol field.
2021-02-02 18:26:41 +00:00
types.Market `json:"-" yaml:"-"`
2021-02-16 08:30:01 +00:00
TradeService *service.TradeService `json:"-" yaml:"-"`
// These fields will be filled from the config file (it translates YAML to JSON)
2021-02-02 18:26:41 +00:00
Symbol string `json:"symbol" yaml:"symbol"`
2020-11-10 11:06:20 +00:00
// ProfitSpread is the fixed profit spread you want to submit the sell order
2021-02-02 18:26:41 +00:00
ProfitSpread fixedpoint.Value `json:"profitSpread" yaml:"profitSpread"`
2020-11-05 07:04:56 +00:00
// GridNum is the grid number, how many orders you want to post on the orderbook.
2021-02-02 18:26:41 +00:00
GridNum int `json:"gridNumber" yaml:"gridNumber"`
2021-02-02 18:26:41 +00:00
UpperPrice fixedpoint.Value `json:"upperPrice" yaml:"upperPrice"`
2020-11-10 11:06:20 +00:00
2021-02-02 18:26:41 +00:00
LowerPrice fixedpoint.Value `json:"lowerPrice" yaml:"lowerPrice"`
2020-11-10 11:06:20 +00:00
// Quantity is the quantity you want to submit for each order.
Quantity fixedpoint.Value `json:"quantity,omitempty"`
2021-02-02 18:26:41 +00:00
// FixedAmount is used for fixed amount (dynamic quantity) if you don't want to use fixed quantity.
FixedAmount fixedpoint.Value `json:"amount,omitempty" yaml:"amount"`
2021-01-06 05:31:17 +00:00
// Long means you want to hold more base asset than the quote asset.
2021-02-02 18:26:41 +00:00
Long bool `json:"long,omitempty" yaml:"long,omitempty"`
orderStore *bbgo.OrderStore
2020-12-31 05:54:32 +00:00
// activeOrders is the locally maintained active order book of the maker orders.
2020-11-05 06:27:22 +00:00
activeOrders *bbgo.LocalActiveOrderBook
position fixedpoint.Value
2020-11-10 11:06:20 +00:00
// any created orders for tracking trades
orders map[uint64]types.Order
groupID int64
}
2021-02-03 01:08:05 +00:00
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) generateGridSellOrders(session *bbgo.ExchangeSession) ([]types.SubmitOrder, error) {
currentPriceFloat, ok := session.LastPrice(s.Symbol)
if !ok {
return nil, fmt.Errorf("%s last price not found, skipping", s.Symbol)
}
currentPrice := fixedpoint.NewFromFloat(currentPriceFloat)
priceRange := s.UpperPrice - s.LowerPrice
if priceRange <= 0 {
return nil, fmt.Errorf("upper price %f should not be less than or equal to lower price %f", s.UpperPrice.Float64(), s.LowerPrice.Float64())
}
numGrids := fixedpoint.NewFromInt(s.GridNum)
gridSpread := priceRange.Div(numGrids)
startPrice := fixedpoint.Max(s.LowerPrice, currentPrice+gridSpread)
if startPrice > s.UpperPrice {
return nil, fmt.Errorf("current price %f exceeded the upper price boundary %f",
currentPrice.Float64(),
s.UpperPrice.Float64())
}
2020-12-29 10:18:32 +00:00
balances := session.Account.Balances()
baseBalance, ok := balances[s.Market.BaseCurrency]
if !ok {
return nil, fmt.Errorf("base balance %s not found", s.Market.BaseCurrency)
}
if baseBalance.Available == 0 {
return nil, fmt.Errorf("base balance %s is zero: %+v", s.Market.BaseCurrency, baseBalance)
}
log.Infof("placing grid sell orders from %f ~ %f, grid spread %f",
2021-02-08 05:21:22 +00:00
startPrice.Float64(),
s.UpperPrice.Float64(),
gridSpread.Float64())
var orders []types.SubmitOrder
for price := startPrice; s.LowerPrice <= price && price <= s.UpperPrice; price += gridSpread {
quantity := s.Quantity
if s.FixedAmount > 0 {
quantity = s.FixedAmount.Div(price)
}
// quoteQuantity := price.Mul(quantity)
if baseBalance.Available < quantity {
return orders, fmt.Errorf("base balance %f is not enough, stop generating orders", baseBalance.Available.Float64())
}
orders = append(orders, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimit,
Market: s.Market,
Quantity: quantity.Float64(),
Price: price.Float64(),
TimeInForce: "GTC",
GroupID: s.groupID,
})
baseBalance.Available -= quantity
}
return orders, nil
}
func (s *Strategy) generateGridBuyOrders(session *bbgo.ExchangeSession) ([]types.SubmitOrder, error) {
currentPriceFloat, ok := session.LastPrice(s.Symbol)
2020-11-10 11:06:20 +00:00
if !ok {
return nil, fmt.Errorf("%s last price not found, skipping", s.Symbol)
}
currentPrice := fixedpoint.NewFromFloat(currentPriceFloat)
2020-11-10 11:06:20 +00:00
priceRange := s.UpperPrice - s.LowerPrice
if priceRange <= 0 {
return nil, fmt.Errorf("upper price %f should not be less than or equal to lower price %f", s.UpperPrice.Float64(), s.LowerPrice.Float64())
}
numGrids := fixedpoint.NewFromInt(s.GridNum)
gridSpread := priceRange.Div(numGrids)
startPrice := fixedpoint.Min(s.UpperPrice, currentPrice-gridSpread)
2020-12-29 10:18:32 +00:00
if startPrice < s.LowerPrice {
return nil, fmt.Errorf("current price %f exceeded the lower price boundary %f",
currentPrice.Float64(),
s.UpperPrice.Float64())
}
balances := session.Account.Balances()
balance, ok := balances[s.Market.QuoteCurrency]
if !ok {
return nil, fmt.Errorf("quote balance %s not found", s.Market.QuoteCurrency)
}
if balance.Available == 0 {
return nil, fmt.Errorf("quote balance %s is zero: %+v", s.Market.QuoteCurrency, balance)
}
log.Infof("placing grid buy orders from %f to %f, grid spread %f",
(currentPrice - gridSpread).Float64(),
s.LowerPrice.Float64(),
gridSpread.Float64())
var orders []types.SubmitOrder
for price := startPrice; s.LowerPrice <= price && price <= s.UpperPrice; price -= gridSpread {
quantity := s.Quantity
if s.FixedAmount > 0 {
quantity = s.FixedAmount.Div(price)
}
quoteQuantity := price.Mul(quantity)
if balance.Available < quoteQuantity {
return orders, fmt.Errorf("quote balance %f is not enough for %f, stop generating orders",
balance.Available.Float64(),
quoteQuantity.Float64())
2020-11-10 11:06:20 +00:00
}
orders = append(orders, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeBuy,
Type: types.OrderTypeLimit,
Market: s.Market,
Quantity: quantity.Float64(),
Price: price.Float64(),
TimeInForce: "GTC",
GroupID: s.groupID,
})
balance.Available -= quoteQuantity
}
return orders, nil
}
func (s *Strategy) placeGridOrders(orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
log.Infof("placing grid orders...")
sellOrders, err := s.generateGridSellOrders(session)
if err != nil {
log.Warn(err.Error())
}
if len(sellOrders) > 0 {
createdSellOrders, err := orderExecutor.SubmitOrders(context.Background(), sellOrders...)
if err != nil {
log.WithError(err).Error(err.Error())
} else {
s.activeOrders.Add(createdSellOrders...)
2020-11-10 11:06:20 +00:00
}
}
buyOrders, err := s.generateGridBuyOrders(session)
if err != nil {
log.Warn(err.Error())
}
if len(buyOrders) > 0 {
createdBuyOrders, err := orderExecutor.SubmitOrders(context.Background(), buyOrders...)
if err != nil {
log.WithError(err).Error(err.Error())
} else {
s.activeOrders.Add(createdBuyOrders...)
}
}
}
2020-11-10 11:06:20 +00:00
func (s *Strategy) tradeUpdateHandler(trade types.Trade) {
if trade.Symbol != s.Symbol {
return
}
if s.orderStore.Exists(trade.OrderID) {
2020-11-10 11:06:20 +00:00
log.Infof("received trade update of order %d: %+v", trade.OrderID, trade)
switch trade.Side {
case types.SideTypeBuy:
s.position.AtomicAdd(fixedpoint.NewFromFloat(trade.Quantity))
2020-11-10 11:06:20 +00:00
case types.SideTypeSell:
s.position.AtomicAdd(-fixedpoint.NewFromFloat(trade.Quantity))
2020-11-10 11:06:20 +00:00
}
}
2020-11-10 11:06:20 +00:00
}
2020-11-10 11:06:20 +00:00
func (s *Strategy) submitReverseOrder(order types.Order) {
var side = order.Side.Reverse()
var price = order.Price
2020-12-31 06:29:23 +00:00
var quantity = order.Quantity
2020-11-10 11:06:20 +00:00
switch side {
case types.SideTypeSell:
price += s.ProfitSpread.Float64()
case types.SideTypeBuy:
price -= s.ProfitSpread.Float64()
2020-11-05 07:04:56 +00:00
}
2021-02-02 18:26:41 +00:00
if s.FixedAmount > 0 {
quantity = s.FixedAmount.Float64() / price
2021-01-06 05:31:17 +00:00
} else if s.Long {
// long = use the same amount to buy more quantity back
// the original amount
var amount = order.Price * order.Quantity
2020-12-31 05:54:32 +00:00
quantity = amount / price
}
2020-11-10 11:06:20 +00:00
submitOrder := types.SubmitOrder{
Symbol: s.Symbol,
Side: side,
Type: types.OrderTypeLimit,
2020-12-31 05:54:32 +00:00
Quantity: quantity,
2020-11-10 11:06:20 +00:00
Price: price,
TimeInForce: "GTC",
GroupID: s.groupID,
}
2020-11-10 11:06:20 +00:00
log.Infof("submitting reverse order: %s against %s", submitOrder.String(), order.String())
2020-11-05 07:04:56 +00:00
2020-11-10 11:06:20 +00:00
createdOrders, err := s.OrderExecutor.SubmitOrders(context.Background(), submitOrder)
if err != nil {
log.WithError(err).Errorf("can not place orders")
return
}
2020-11-10 06:18:54 +00:00
2020-12-17 08:22:43 +00:00
s.orderStore.Add(createdOrders...)
2020-11-10 11:06:20 +00:00
s.activeOrders.Add(createdOrders...)
}
2020-11-10 11:06:20 +00:00
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2021-02-16 08:30:01 +00:00
// do some basic validation
if s.GridNum == 0 {
2020-11-10 11:06:20 +00:00
s.GridNum = 10
}
2020-12-31 05:54:32 +00:00
if s.UpperPrice <= s.LowerPrice {
return fmt.Errorf("upper price (%f) should not be less than lower price (%f)", s.UpperPrice.Float64(), s.LowerPrice.Float64())
}
2021-02-16 08:30:01 +00:00
position, ok := session.Position(s.Symbol)
if !ok {
return fmt.Errorf("position not found")
}
log.Infof("position: %+v", position)
instanceID := fmt.Sprintf("grid-%s-%d", s.Symbol, s.GridNum)
s.groupID = generateGroupID(instanceID)
log.Infof("using group id %d from fnv(%s)", s.groupID, instanceID)
2021-01-21 06:51:37 +00:00
s.orderStore = bbgo.NewOrderStore(s.Symbol)
s.orderStore.BindStream(session.Stream)
2020-10-29 13:10:13 +00:00
// we don't persist orders so that we can not clear the previous orders for now. just need time to support this.
s.activeOrders = bbgo.NewLocalActiveOrderBook()
s.activeOrders.OnFilled(s.submitReverseOrder)
s.activeOrders.BindStream(session.Stream)
2020-10-29 13:10:13 +00:00
2020-11-12 06:50:08 +00:00
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
2020-11-12 06:59:47 +00:00
defer wg.Done()
2020-11-12 06:50:08 +00:00
log.Infof("canceling active orders...")
if err := session.Exchange.CancelOrders(ctx, s.activeOrders.Orders()...); err != nil {
log.WithError(err).Errorf("cancel order error")
}
})
2020-11-10 11:06:20 +00:00
session.Stream.OnTradeUpdate(s.tradeUpdateHandler)
session.Stream.OnConnect(func() {
s.placeGridOrders(orderExecutor, session)
2020-11-05 07:04:56 +00:00
})
return nil
}
func generateGroupID(s string) int64 {
h := fnv.New32a()
h.Write([]byte(s))
return int64(h.Sum32())
}