bbgo_origin/pkg/strategy/fixedmaker/strategy.go

233 lines
6.1 KiB
Go
Raw Normal View History

2023-03-10 08:29:49 +00:00
package fixedmaker
import (
"context"
"fmt"
"sync"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
2023-09-19 06:51:04 +00:00
"github.com/c9s/bbgo/pkg/strategy/common"
2023-03-10 08:29:49 +00:00
"github.com/c9s/bbgo/pkg/types"
)
const ID = "fixedmaker"
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
// Fixed spread market making strategy
type Strategy struct {
*common.Strategy
2023-09-19 06:51:04 +00:00
2023-09-28 17:06:58 +00:00
Environment *bbgo.Environment
Market types.Market
2023-03-10 08:29:49 +00:00
2023-09-28 17:06:58 +00:00
Symbol string `json:"symbol"`
Interval types.Interval `json:"interval"`
Quantity fixedpoint.Value `json:"quantity"`
HalfSpread fixedpoint.Value `json:"halfSpread"`
OrderType types.OrderType `json:"orderType"`
DryRun bool `json:"dryRun"`
2023-03-15 19:15:07 +00:00
2023-12-21 08:29:46 +00:00
InventorySkew InventorySkew `json:"inventorySkew"`
2023-03-10 08:29:49 +00:00
activeOrderBook *bbgo.ActiveOrderBook
}
2023-03-10 09:39:31 +00:00
func (s *Strategy) Defaults() error {
if s.OrderType == "" {
2023-09-19 06:51:04 +00:00
log.Infof("order type is not set, using limit maker order type")
2023-03-10 09:39:31 +00:00
s.OrderType = types.OrderTypeLimitMaker
}
return nil
}
2023-03-10 08:29:49 +00:00
func (s *Strategy) Initialize() error {
if s.Strategy == nil {
s.Strategy = &common.Strategy{}
}
2023-03-10 08:29:49 +00:00
return nil
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
func (s *Strategy) Validate() error {
if s.Quantity.Float64() <= 0 {
return fmt.Errorf("quantity should be positive")
}
2023-09-28 17:06:58 +00:00
if s.HalfSpread.Float64() <= 0 {
2023-10-11 04:12:57 +00:00
return fmt.Errorf("halfSpread should be positive")
2023-03-10 08:29:49 +00:00
}
2023-12-21 08:29:46 +00:00
if err := s.InventorySkew.Validate(); err != nil {
return err
}
2023-03-10 08:29:49 +00:00
return nil
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
2023-10-05 06:36:08 +00:00
if !s.CircuitBreakLossThreshold.IsZero() {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.CircuitBreakEMA.Interval})
}
2023-03-10 08:29:49 +00:00
}
func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2023-09-19 06:51:04 +00:00
s.Strategy.Initialize(ctx, s.Environment, session, s.Market, ID, s.InstanceID())
2023-03-10 08:29:49 +00:00
s.activeOrderBook = bbgo.NewActiveOrderBook(s.Symbol)
s.activeOrderBook.BindStream(session.UserDataStream)
s.activeOrderBook.OnFilled(func(order types.Order) {
2023-10-05 06:36:08 +00:00
if s.IsHalted(order.UpdateTime.Time()) {
log.Infof("circuit break halted")
return
}
2023-03-10 08:29:49 +00:00
if s.activeOrderBook.NumOfOrders() == 0 {
2023-10-05 06:36:08 +00:00
log.Infof("no active orders, placing orders...")
s.placeOrders(ctx)
2023-03-10 08:29:49 +00:00
}
})
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
2023-09-28 17:06:58 +00:00
log.Infof("%s", kline.String())
2023-10-05 06:36:08 +00:00
if s.IsHalted(kline.EndTime.Time()) {
log.Infof("circuit break halted")
return
}
if kline.Interval == s.Interval {
s.cancelOrders(ctx)
s.placeOrders(ctx)
}
2023-03-10 08:29:49 +00:00
})
// the shutdown handler, you can cancel all orders
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
2023-09-19 06:51:04 +00:00
_ = s.OrderExecutor.GracefulCancel(ctx)
2024-05-14 10:54:24 +00:00
bbgo.Sync(ctx, s)
2023-03-10 08:29:49 +00:00
})
2023-10-05 06:36:08 +00:00
2023-03-10 08:29:49 +00:00
return nil
}
2023-10-05 06:36:08 +00:00
func (s *Strategy) cancelOrders(ctx context.Context) {
2023-12-21 08:29:46 +00:00
if err := s.activeOrderBook.GracefulCancel(ctx, s.Session.Exchange); err != nil {
2023-03-10 08:29:49 +00:00
log.WithError(err).Errorf("failed to cancel orders")
}
2023-10-05 06:36:08 +00:00
}
2023-03-10 08:29:49 +00:00
2023-10-05 06:36:08 +00:00
func (s *Strategy) placeOrders(ctx context.Context) {
orders, err := s.generateOrders(ctx)
2023-03-10 08:29:49 +00:00
if err != nil {
2023-10-05 06:36:08 +00:00
log.WithError(err).Error("failed to generate orders")
2023-03-10 08:29:49 +00:00
return
}
2023-10-05 06:36:08 +00:00
log.Infof("orders: %+v", orders)
2023-03-10 08:29:49 +00:00
if s.DryRun {
log.Infof("dry run, not submitting orders")
return
}
2023-10-05 06:36:08 +00:00
createdOrders, err := s.OrderExecutor.SubmitOrders(ctx, orders...)
2023-03-10 08:29:49 +00:00
if err != nil {
log.WithError(err).Error("failed to submit orders")
return
}
log.Infof("created orders: %+v", createdOrders)
s.activeOrderBook.Add(createdOrders...)
}
2023-10-05 06:36:08 +00:00
func (s *Strategy) generateOrders(ctx context.Context) ([]types.SubmitOrder, error) {
2023-03-15 11:00:07 +00:00
orders := []types.SubmitOrder{}
2023-09-19 06:51:04 +00:00
baseBalance, ok := s.Session.GetAccount().Balance(s.Market.BaseCurrency)
2023-03-10 08:29:49 +00:00
if !ok {
return nil, fmt.Errorf("base currency %s balance not found", s.Market.BaseCurrency)
}
log.Infof("base balance: %+v", baseBalance)
2023-09-19 06:51:04 +00:00
quoteBalance, ok := s.Session.GetAccount().Balance(s.Market.QuoteCurrency)
2023-03-10 08:29:49 +00:00
if !ok {
return nil, fmt.Errorf("quote currency %s balance not found", s.Market.QuoteCurrency)
}
log.Infof("quote balance: %+v", quoteBalance)
2023-09-19 06:51:04 +00:00
ticker, err := s.Session.Exchange.QueryTicker(ctx, s.Symbol)
2023-03-10 08:29:49 +00:00
if err != nil {
return nil, err
}
midPrice := ticker.Buy.Add(ticker.Sell).Div(fixedpoint.NewFromFloat(2.0))
log.Infof("mid price: %+v", midPrice)
2023-03-15 11:00:07 +00:00
// calculate bid and ask price
2023-09-28 17:12:53 +00:00
// sell price = mid price * (1 + r))
// buy price = mid price * (1 - r))
2023-09-28 17:06:58 +00:00
sellPrice := midPrice.Mul(fixedpoint.One.Add(s.HalfSpread)).Round(s.Market.PricePrecision, fixedpoint.Up)
buyPrice := midPrice.Mul(fixedpoint.One.Sub(s.HalfSpread)).Round(s.Market.PricePrecision, fixedpoint.Down)
log.Infof("sell price: %s, buy price: %s", sellPrice.String(), buyPrice.String())
2023-03-10 08:29:49 +00:00
2023-12-21 08:29:46 +00:00
buyQuantity := s.Quantity
sellQuantity := s.Quantity
if !s.InventorySkew.InventoryRangeMultiplier.IsZero() {
ratios := s.InventorySkew.CalculateBidAskRatios(
s.Quantity,
midPrice,
baseBalance.Total(),
quoteBalance.Total(),
)
2023-12-21 08:34:05 +00:00
log.Infof("bid ratio: %s, ask ratio: %s", ratios.BidRatio.String(), ratios.AskRatio.String())
buyQuantity = s.Quantity.Mul(ratios.BidRatio)
sellQuantity = s.Quantity.Mul(ratios.AskRatio)
2023-12-21 08:29:46 +00:00
log.Infof("buy quantity: %s, sell quantity: %s", buyQuantity.String(), sellQuantity.String())
}
2023-03-10 08:29:49 +00:00
// check balance and generate orders
2023-09-28 17:06:58 +00:00
amount := s.Quantity.Mul(buyPrice)
2023-03-10 08:29:49 +00:00
if quoteBalance.Available.Compare(amount) > 0 {
orders = append(orders, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeBuy,
2023-03-10 09:39:31 +00:00
Type: s.OrderType,
2023-09-28 17:06:58 +00:00
Price: buyPrice,
2023-12-21 08:29:46 +00:00
Quantity: buyQuantity,
2023-03-10 08:29:49 +00:00
})
} else {
log.Infof("not enough quote balance to buy, available: %s, amount: %s", quoteBalance.Available, amount)
}
if baseBalance.Available.Compare(s.Quantity) > 0 {
orders = append(orders, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
2023-03-10 09:39:31 +00:00
Type: s.OrderType,
2023-09-28 17:06:58 +00:00
Price: sellPrice,
2023-12-21 08:29:46 +00:00
Quantity: sellQuantity,
2023-03-10 08:29:49 +00:00
})
} else {
log.Infof("not enough base balance to sell, available: %s, quantity: %s", baseBalance.Available, s.Quantity)
}
return orders, nil
}