bbgo_origin/pkg/strategy/fixedmaker/strategy.go

249 lines
7.0 KiB
Go
Raw Normal View History

2023-03-10 08:29:49 +00:00
package fixedmaker
import (
"context"
"fmt"
"sync"
2023-09-21 06:57:55 +00:00
"time"
2023-03-10 08:29:49 +00:00
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
2023-09-19 06:51:04 +00:00
indicatorv2 "github.com/c9s/bbgo/pkg/indicator/v2"
"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 {
2023-09-19 06:51:04 +00:00
*common.Strategy
2023-03-10 08:29:49 +00:00
Environment *bbgo.Environment
StandardIndicatorSet *bbgo.StandardIndicatorSet
Market types.Market
2023-03-10 09:39:31 +00:00
Interval types.Interval `json:"interval"`
Symbol string `json:"symbol"`
Quantity fixedpoint.Value `json:"quantity"`
HalfSpreadRatio fixedpoint.Value `json:"halfSpreadRatio"`
OrderType types.OrderType `json:"orderType"`
DryRun bool `json:"dryRun"`
2023-03-10 08:29:49 +00:00
2023-03-15 11:00:07 +00:00
// SkewFactor is used to calculate the skew of bid/ask price
SkewFactor fixedpoint.Value `json:"skewFactor"`
TargetWeight fixedpoint.Value `json:"targetWeight"`
2023-03-15 19:15:07 +00:00
// replace halfSpreadRatio by ATR
ATRMultiplier fixedpoint.Value `json:"atrMultiplier"`
ATRWindow int `json:"atrWindow"`
2023-03-10 08:29:49 +00:00
activeOrderBook *bbgo.ActiveOrderBook
2023-09-19 06:51:04 +00:00
atr *indicatorv2.ATRStream
2023-03-10 08:29:49 +00:00
}
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
}
2023-03-15 19:15:07 +00:00
if s.ATRWindow == 0 {
2023-09-19 06:51:04 +00:00
log.Infof("atr window is not set, using default value 14")
2023-03-15 19:15:07 +00:00
s.ATRWindow = 14
}
2023-03-10 09:39:31 +00:00
return nil
}
2023-03-10 08:29:49 +00:00
func (s *Strategy) Initialize() error {
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-03-10 09:39:31 +00:00
if s.HalfSpreadRatio.Float64() <= 0 {
2023-03-10 08:29:49 +00:00
return fmt.Errorf("halfSpreadRatio should be positive")
}
2023-03-15 19:15:07 +00:00
if s.SkewFactor.Float64() < 0 {
return fmt.Errorf("skewFactor should be non-negative")
}
if s.ATRMultiplier.Float64() < 0 {
return fmt.Errorf("atrMultiplier should be non-negative")
}
if s.ATRWindow < 0 {
return fmt.Errorf("atrWindow should be non-negative")
}
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})
}
func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2023-09-19 06:51:04 +00:00
s.Strategy = &common.Strategy{}
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)
2023-09-19 06:51:04 +00:00
s.atr = session.Indicators(s.Symbol).ATR(s.Interval, s.ATRWindow)
2023-03-15 19:15:07 +00:00
2023-03-10 08:29:49 +00:00
session.UserDataStream.OnStart(func() {
// you can place orders here when bbgo is started, this will be called only once.
})
s.activeOrderBook.OnFilled(func(order types.Order) {
if s.activeOrderBook.NumOfOrders() == 0 {
log.Infof("no active orders, replenish")
2023-09-21 06:57:55 +00:00
s.replenish(ctx, order.UpdateTime.Time())
2023-03-10 08:29:49 +00:00
}
})
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
log.Infof("%+v", kline)
s.cancelOrders(ctx)
2023-09-21 06:57:55 +00:00
s.replenish(ctx, kline.EndTime.Time())
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)
2023-03-10 08:29:49 +00:00
})
return nil
}
func (s *Strategy) cancelOrders(ctx context.Context) {
2023-09-19 06:51:04 +00:00
if err := s.Session.Exchange.CancelOrders(ctx, s.activeOrderBook.Orders()...); err != nil {
2023-03-10 08:29:49 +00:00
log.WithError(err).Errorf("failed to cancel orders")
}
}
2023-09-21 06:57:55 +00:00
func (s *Strategy) replenish(ctx context.Context, t time.Time) {
if s.IsHalted(t) {
log.Infof("circuit break halted, not replenishing")
return
}
2023-03-10 08:29:49 +00:00
submitOrders, err := s.generateSubmitOrders(ctx)
if err != nil {
log.WithError(err).Error("failed to generate submit orders")
return
}
log.Infof("submit orders: %+v", submitOrders)
if s.DryRun {
log.Infof("dry run, not submitting orders")
return
}
2023-09-19 06:51:04 +00:00
createdOrders, err := s.OrderExecutor.SubmitOrders(ctx, submitOrders...)
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...)
}
func (s *Strategy) generateSubmitOrders(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 19:15:07 +00:00
if s.ATRMultiplier.Float64() > 0 {
atr := fixedpoint.NewFromFloat(s.atr.Last(0))
2023-03-15 19:15:07 +00:00
log.Infof("atr: %s", atr.String())
s.HalfSpreadRatio = s.ATRMultiplier.Mul(atr).Div(midPrice)
log.Infof("half spread ratio: %s", s.HalfSpreadRatio.String())
}
2023-03-16 19:10:03 +00:00
// calcualte skew by the difference between base weight and target weight
baseValue := baseBalance.Total().Mul(midPrice)
baseWeight := baseValue.Div(baseValue.Add(quoteBalance.Total()))
skew := s.SkewFactor.Mul(s.HalfSpreadRatio).Mul(baseWeight.Sub(s.TargetWeight))
// let the skew be in the range of [-r, r]
skew = skew.Clamp(s.HalfSpreadRatio.Neg(), s.HalfSpreadRatio)
2023-03-15 11:00:07 +00:00
// calculate bid and ask price
2023-03-16 19:10:03 +00:00
// bid price = mid price * (1 - r - skew))
2023-03-15 11:00:07 +00:00
bidSpreadRatio := fixedpoint.Max(s.HalfSpreadRatio.Add(skew), fixedpoint.Zero)
bidPrice := midPrice.Mul(fixedpoint.One.Sub(bidSpreadRatio))
log.Infof("bid price: %s", bidPrice.String())
2023-03-16 19:10:03 +00:00
// ask price = mid price * (1 + r - skew))
2023-03-15 11:00:07 +00:00
askSrasedRatio := fixedpoint.Max(s.HalfSpreadRatio.Sub(skew), fixedpoint.Zero)
askPrice := midPrice.Mul(fixedpoint.One.Add(askSrasedRatio))
log.Infof("ask price: %s", askPrice.String())
2023-03-10 08:29:49 +00:00
// check balance and generate orders
2023-03-15 11:00:07 +00:00
amount := s.Quantity.Mul(bidPrice)
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-03-15 11:00:07 +00:00
Price: bidPrice,
2023-03-10 08:29:49 +00:00
Quantity: s.Quantity,
})
} 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-03-15 11:00:07 +00:00
Price: askPrice,
2023-03-10 08:29:49 +00:00
Quantity: s.Quantity,
})
} else {
log.Infof("not enough base balance to sell, available: %s, quantity: %s", baseBalance.Available, s.Quantity)
}
return orders, nil
}