bbgo_origin/pkg/strategy/scmaker/strategy.go

512 lines
15 KiB
Go
Raw Normal View History

2023-06-13 04:22:59 +00:00
package scmaker
import (
"context"
"fmt"
"math"
2023-06-19 07:22:43 +00:00
"sync"
"time"
2023-06-13 04:22:59 +00:00
log "github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
. "github.com/c9s/bbgo/pkg/indicator/v2"
"github.com/c9s/bbgo/pkg/risk/riskcontrol"
2023-07-09 11:55:36 +00:00
"github.com/c9s/bbgo/pkg/strategy/common"
2023-06-13 04:22:59 +00:00
"github.com/c9s/bbgo/pkg/types"
)
const ID = "scmaker"
var ten = fixedpoint.NewFromInt(10)
type advancedOrderCancelApi interface {
CancelAllOrders(ctx context.Context) ([]types.Order, error)
CancelOrdersBySymbol(ctx context.Context, symbol string) ([]types.Order, error)
}
2023-06-13 04:22:59 +00:00
type BollingerConfig struct {
Interval types.Interval `json:"interval"`
Window int `json:"window"`
K float64 `json:"k"`
}
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
2023-06-14 07:16:48 +00:00
// Strategy scmaker is a stable coin market maker
2023-06-13 04:22:59 +00:00
type Strategy struct {
2023-07-09 11:55:36 +00:00
*common.Strategy
2023-06-13 04:22:59 +00:00
Environment *bbgo.Environment
Market types.Market
Symbol string `json:"symbol"`
NumOfLiquidityLayers int `json:"numOfLiquidityLayers"`
LiquidityUpdateInterval types.Interval `json:"liquidityUpdateInterval"`
PriceRangeBollinger *BollingerConfig `json:"priceRangeBollinger"`
StrengthInterval types.Interval `json:"strengthInterval"`
AdjustmentUpdateInterval types.Interval `json:"adjustmentUpdateInterval"`
MidPriceEMA *types.IntervalWindow `json:"midPriceEMA"`
LiquiditySlideRule *bbgo.SlideRule `json:"liquidityScale"`
LiquidityLayerTickSize fixedpoint.Value `json:"liquidityLayerTickSize"`
2023-07-03 08:22:01 +00:00
LiquiditySkew fixedpoint.Value `json:"liquiditySkew"`
2023-06-13 04:22:59 +00:00
2023-06-19 05:46:45 +00:00
MaxExposure fixedpoint.Value `json:"maxExposure"`
2023-06-14 08:20:37 +00:00
MinProfit fixedpoint.Value `json:"minProfit"`
// risk related parameters
PositionHardLimit fixedpoint.Value `json:"positionHardLimit"`
MaxPositionQuantity fixedpoint.Value `json:"maxPositionQuantity"`
CircuitBreakLossThreshold fixedpoint.Value `json:"circuitBreakLossThreshold"`
CircuitBreakEMA types.IntervalWindow `json:"circuitBreakEMA"`
2023-06-13 04:22:59 +00:00
liquidityOrderBook, adjustmentOrderBook *bbgo.ActiveOrderBook
book *types.StreamOrderBook
liquidityScale bbgo.Scale
// indicators
ewma *EWMAStream
boll *BOLLStream
2023-06-13 04:22:59 +00:00
intensity *IntensityStream
positionRiskControl *riskcontrol.PositionRiskControl
circuitBreakRiskControl *riskcontrol.CircuitBreakRiskControl
2023-06-13 04:22:59 +00:00
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{})
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.AdjustmentUpdateInterval})
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.LiquidityUpdateInterval})
if s.MidPriceEMA != nil {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.MidPriceEMA.Interval})
}
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2023-07-09 11:55:36 +00:00
s.Strategy = &common.Strategy{}
2023-07-09 13:23:42 +00:00
s.Strategy.Initialize(ctx, s.Environment, session, s.Market, ID, s.InstanceID())
2023-06-13 04:22:59 +00:00
s.book = types.NewStreamBook(s.Symbol)
s.book.BindStream(session.UserDataStream)
s.liquidityOrderBook = bbgo.NewActiveOrderBook(s.Symbol)
s.liquidityOrderBook.BindStream(session.UserDataStream)
2023-06-13 04:22:59 +00:00
s.adjustmentOrderBook = bbgo.NewActiveOrderBook(s.Symbol)
s.adjustmentOrderBook.BindStream(session.UserDataStream)
2023-06-13 04:22:59 +00:00
if !s.PositionHardLimit.IsZero() && !s.MaxPositionQuantity.IsZero() {
log.Infof("positionHardLimit and maxPositionQuantity are configured, setting up PositionRiskControl...")
s.positionRiskControl = riskcontrol.NewPositionRiskControl(s.OrderExecutor, s.PositionHardLimit, s.MaxPositionQuantity)
}
if !s.CircuitBreakLossThreshold.IsZero() {
log.Infof("circuitBreakLossThreshold is configured, setting up CircuitBreakRiskControl...")
s.circuitBreakRiskControl = riskcontrol.NewCircuitBreakRiskControl(
s.Position,
session.Indicators(s.Symbol).EWMA(s.CircuitBreakEMA),
s.CircuitBreakLossThreshold,
s.ProfitStats,
24*time.Hour)
}
2023-06-13 04:22:59 +00:00
scale, err := s.LiquiditySlideRule.Scale()
if err != nil {
return err
}
if err := scale.Solve(); err != nil {
return err
}
if cancelApi, ok := session.Exchange.(advancedOrderCancelApi); ok {
_, _ = cancelApi.CancelOrdersBySymbol(ctx, s.Symbol)
}
2023-06-13 04:22:59 +00:00
s.liquidityScale = scale
s.initializeMidPriceEMA(session)
s.initializePriceRangeBollinger(session)
s.initializeIntensityIndicator(session)
session.UserDataStream.OnStart(func() {
s.placeLiquidityOrders(ctx)
})
2023-06-14 08:20:37 +00:00
session.MarketDataStream.OnKLineClosed(func(k types.KLine) {
if k.Interval == s.AdjustmentUpdateInterval {
s.placeAdjustmentOrders(ctx)
}
2023-06-13 04:22:59 +00:00
2023-06-14 08:20:37 +00:00
if k.Interval == s.LiquidityUpdateInterval {
s.placeLiquidityOrders(ctx)
}
})
2023-06-13 04:22:59 +00:00
2023-06-19 07:22:43 +00:00
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
err := s.liquidityOrderBook.GracefulCancel(ctx, s.Session.Exchange)
2023-06-19 07:22:43 +00:00
logErr(err, "unable to cancel liquidity orders")
err = s.adjustmentOrderBook.GracefulCancel(ctx, s.Session.Exchange)
2023-06-19 07:22:43 +00:00
logErr(err, "unable to cancel adjustment orders")
})
2023-06-13 04:22:59 +00:00
return nil
}
func (s *Strategy) preloadKLines(inc *KLineStream, session *bbgo.ExchangeSession, symbol string, interval types.Interval) {
2023-06-19 09:03:38 +00:00
if store, ok := session.MarketDataStore(symbol); ok {
if kLinesData, ok := store.KLinesOfInterval(interval); ok {
for _, k := range *kLinesData {
inc.EmitUpdate(k)
}
}
}
}
2023-06-13 04:22:59 +00:00
func (s *Strategy) initializeMidPriceEMA(session *bbgo.ExchangeSession) {
kLines := KLines(session.MarketDataStream, s.Symbol, s.MidPriceEMA.Interval)
s.ewma = EWMA2(ClosePrices(kLines), s.MidPriceEMA.Window)
2023-06-19 09:03:38 +00:00
s.preloadKLines(kLines, session, s.Symbol, s.MidPriceEMA.Interval)
2023-06-13 04:22:59 +00:00
}
func (s *Strategy) initializeIntensityIndicator(session *bbgo.ExchangeSession) {
kLines := KLines(session.MarketDataStream, s.Symbol, s.StrengthInterval)
2023-06-13 04:22:59 +00:00
s.intensity = Intensity(kLines, 10)
2023-06-19 09:03:38 +00:00
s.preloadKLines(kLines, session, s.Symbol, s.StrengthInterval)
2023-06-13 04:22:59 +00:00
}
func (s *Strategy) initializePriceRangeBollinger(session *bbgo.ExchangeSession) {
kLines := KLines(session.MarketDataStream, s.Symbol, s.PriceRangeBollinger.Interval)
closePrices := ClosePrices(kLines)
s.boll = BOLL(closePrices, s.PriceRangeBollinger.Window, s.PriceRangeBollinger.K)
2023-06-19 09:03:38 +00:00
s.preloadKLines(kLines, session, s.Symbol, s.PriceRangeBollinger.Interval)
2023-06-13 04:22:59 +00:00
}
func (s *Strategy) placeAdjustmentOrders(ctx context.Context) {
_ = s.adjustmentOrderBook.GracefulCancel(ctx, s.Session.Exchange)
2023-06-14 08:20:37 +00:00
2023-06-13 04:22:59 +00:00
if s.Position.IsDust() {
return
}
2023-06-14 08:20:37 +00:00
ticker, err := s.Session.Exchange.QueryTicker(ctx, s.Symbol)
2023-06-14 08:20:37 +00:00
if logErr(err, "unable to query ticker") {
return
}
if _, err := s.Session.UpdateAccount(ctx); err != nil {
logErr(err, "unable to update account")
return
}
baseBal, _ := s.Session.Account.Balance(s.Market.BaseCurrency)
quoteBal, _ := s.Session.Account.Balance(s.Market.QuoteCurrency)
2023-06-14 08:20:37 +00:00
var adjOrders []types.SubmitOrder
posSize := s.Position.Base.Abs()
tickSize := s.Market.TickSize
2023-06-14 08:20:37 +00:00
if s.Position.IsShort() {
price := profitProtectedPrice(types.SideTypeBuy, s.Position.AverageCost, ticker.Sell.Add(tickSize.Neg()), s.Session.MakerFeeRate, s.MinProfit)
2023-06-14 08:20:37 +00:00
quoteQuantity := fixedpoint.Min(price.Mul(posSize), quoteBal.Available)
bidQuantity := quoteQuantity.Div(price)
if s.Market.IsDustQuantity(bidQuantity, price) {
return
}
adjOrders = append(adjOrders, types.SubmitOrder{
Symbol: s.Symbol,
Type: types.OrderTypeLimitMaker,
Side: types.SideTypeBuy,
Price: price,
Quantity: bidQuantity,
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
})
} else if s.Position.IsLong() {
price := profitProtectedPrice(types.SideTypeSell, s.Position.AverageCost, ticker.Buy.Add(tickSize), s.Session.MakerFeeRate, s.MinProfit)
2023-06-14 08:20:37 +00:00
askQuantity := fixedpoint.Min(posSize, baseBal.Available)
if s.Market.IsDustQuantity(askQuantity, price) {
return
}
adjOrders = append(adjOrders, types.SubmitOrder{
Symbol: s.Symbol,
Type: types.OrderTypeLimitMaker,
Side: types.SideTypeSell,
Price: price,
Quantity: askQuantity,
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
})
}
createdOrders, err := s.OrderExecutor.SubmitOrders(ctx, adjOrders...)
2023-06-14 08:20:37 +00:00
if logErr(err, "unable to place liquidity orders") {
return
}
s.adjustmentOrderBook.Add(createdOrders...)
2023-06-13 04:22:59 +00:00
}
func (s *Strategy) placeLiquidityOrders(ctx context.Context) {
ticker, err := s.Session.Exchange.QueryTicker(ctx, s.Symbol)
if logErr(err, "unable to query ticker") {
return
}
if s.circuitBreakRiskControl != nil && s.circuitBreakRiskControl.IsHalted(ticker.Time) {
log.Warn("circuitBreakRiskControl: trading halted")
return
}
2023-06-13 04:22:59 +00:00
err = s.liquidityOrderBook.GracefulCancel(ctx, s.Session.Exchange)
if logErr(err, "unable to cancel orders") {
2023-06-13 04:22:59 +00:00
return
}
2023-07-03 08:22:01 +00:00
if ticker.Buy.IsZero() && ticker.Sell.IsZero() {
ticker.Sell = ticker.Last.Add(s.Market.TickSize)
ticker.Buy = ticker.Last.Sub(s.Market.TickSize)
} else if ticker.Buy.IsZero() {
ticker.Buy = ticker.Sell.Sub(s.Market.TickSize)
} else if ticker.Sell.IsZero() {
ticker.Sell = ticker.Buy.Add(s.Market.TickSize)
}
if _, err := s.Session.UpdateAccount(ctx); err != nil {
logErr(err, "unable to update account")
return
}
baseBal, _ := s.Session.Account.Balance(s.Market.BaseCurrency)
quoteBal, _ := s.Session.Account.Balance(s.Market.QuoteCurrency)
2023-06-13 04:22:59 +00:00
spread := ticker.Sell.Sub(ticker.Buy)
tickSize := fixedpoint.Max(s.LiquidityLayerTickSize, s.Market.TickSize)
2023-06-13 04:22:59 +00:00
midPriceEMA := s.ewma.Last(0)
midPrice := fixedpoint.NewFromFloat(midPriceEMA)
bandWidth := s.boll.Last(0)
2023-06-14 08:20:37 +00:00
log.Infof("spread: %f mid price ema: %f boll band width: %f", spread.Float64(), midPriceEMA, bandWidth)
2023-06-13 04:22:59 +00:00
2023-07-03 08:22:01 +00:00
sum := s.liquidityScale.Sum(1.0)
askSum := sum
bidSum := sum
log.Infof("liquidity sum: %f / %f", askSum, bidSum)
skew := s.LiquiditySkew.Float64()
useSkew := !s.LiquiditySkew.IsZero()
if useSkew {
askSum = sum / skew
bidSum = sum * skew
log.Infof("adjusted liqudity skew: %f / %f", askSum, bidSum)
}
2023-06-14 07:16:48 +00:00
var bidPrices []fixedpoint.Value
var askPrices []fixedpoint.Value
// calculate and collect prices
2023-06-13 04:22:59 +00:00
for i := 0; i <= s.NumOfLiquidityLayers; i++ {
fi := fixedpoint.NewFromInt(int64(i))
2023-06-15 09:26:04 +00:00
sp := tickSize.Mul(fi)
2023-07-03 08:22:01 +00:00
spreadBidPrice := midPrice.Sub(sp)
spreadAskPrice := midPrice.Add(sp)
bidPrice := ticker.Buy
askPrice := ticker.Sell
if i == s.NumOfLiquidityLayers {
2023-06-14 07:16:48 +00:00
bwf := fixedpoint.NewFromFloat(bandWidth)
2023-07-03 08:22:01 +00:00
bidPrice = fixedpoint.Min(midPrice.Add(bwf.Neg()), spreadBidPrice)
askPrice = fixedpoint.Max(midPrice.Add(bwf), spreadAskPrice)
} else if i > 0 {
2023-07-03 08:22:01 +00:00
bidPrice = spreadBidPrice
askPrice = spreadAskPrice
2023-06-15 09:26:04 +00:00
}
2023-06-19 05:46:45 +00:00
if i > 0 && bidPrice.Compare(ticker.Buy) > 0 {
2023-06-15 09:26:04 +00:00
bidPrice = ticker.Buy.Sub(sp)
}
2023-06-19 05:46:45 +00:00
if i > 0 && askPrice.Compare(ticker.Sell) < 0 {
2023-06-15 09:26:04 +00:00
askPrice = ticker.Sell.Add(sp)
2023-06-13 04:22:59 +00:00
}
bidPrice = s.Market.TruncatePrice(bidPrice)
askPrice = s.Market.TruncatePrice(askPrice)
bidPrices = append(bidPrices, bidPrice)
askPrices = append(askPrices, askPrice)
2023-06-14 07:16:48 +00:00
}
2023-06-14 08:20:37 +00:00
availableBase := baseBal.Available
availableQuote := quoteBal.Available
2023-06-19 05:46:45 +00:00
// check max exposure
if s.MaxExposure.Sign() > 0 {
availableQuote = fixedpoint.Min(availableQuote, s.MaxExposure)
baseQuoteValue := availableBase.Mul(ticker.Sell)
if baseQuoteValue.Compare(s.MaxExposure) > 0 {
availableBase = s.MaxExposure.Div(ticker.Sell)
}
}
makerQuota := &bbgo.QuotaTransaction{}
makerQuota.QuoteAsset.Add(availableQuote)
makerQuota.BaseAsset.Add(availableBase)
2023-06-14 08:20:37 +00:00
log.Infof("balances before liq orders: %s, %s",
baseBal.String(),
quoteBal.String())
if !s.Position.IsDust() {
if s.Position.IsLong() {
availableBase = availableBase.Sub(s.Position.Base)
availableBase = s.Market.RoundDownQuantityByPrecision(availableBase)
} else if s.Position.IsShort() {
posSizeInQuote := s.Position.Base.Mul(ticker.Sell)
availableQuote = availableQuote.Sub(posSizeInQuote)
}
}
2023-07-03 08:22:01 +00:00
askX := availableBase.Float64() / askSum
bidX := availableQuote.Float64() / (bidSum * (fixedpoint.Sum(bidPrices).Float64()))
2023-06-14 07:16:48 +00:00
askX = math.Trunc(askX*1e8) / 1e8
bidX = math.Trunc(bidX*1e8) / 1e8
var liqOrders []types.SubmitOrder
for i := 0; i <= s.NumOfLiquidityLayers; i++ {
bidQuantity := fixedpoint.NewFromFloat(s.liquidityScale.Call(float64(i)) * bidX)
askQuantity := fixedpoint.NewFromFloat(s.liquidityScale.Call(float64(i)) * askX)
bidPrice := bidPrices[i]
askPrice := askPrices[i]
2023-06-13 04:22:59 +00:00
2023-06-14 08:20:37 +00:00
log.Infof("liqudity layer #%d %f/%f = %f/%f", i, askPrice.Float64(), bidPrice.Float64(), askQuantity.Float64(), bidQuantity.Float64())
2023-06-13 04:22:59 +00:00
placeBuy := true
placeSell := true
averageCost := s.Position.AverageCost
// when long position, do not place sell orders below the average cost
if !s.Position.IsDust() {
if s.Position.IsLong() && askPrice.Compare(averageCost) < 0 {
placeSell = false
}
if s.Position.IsShort() && bidPrice.Compare(averageCost) > 0 {
placeBuy = false
}
}
2023-06-14 07:16:48 +00:00
quoteQuantity := bidQuantity.Mul(bidPrice)
2023-06-13 04:22:59 +00:00
2023-06-14 08:20:37 +00:00
if s.Market.IsDustQuantity(bidQuantity, bidPrice) || !makerQuota.QuoteAsset.Lock(quoteQuantity) {
2023-06-13 04:22:59 +00:00
placeBuy = false
}
2023-06-14 08:20:37 +00:00
if s.Market.IsDustQuantity(askQuantity, askPrice) || !makerQuota.BaseAsset.Lock(askQuantity) {
2023-06-13 04:22:59 +00:00
placeSell = false
}
if placeBuy {
liqOrders = append(liqOrders, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeBuy,
Type: types.OrderTypeLimitMaker,
2023-06-14 07:16:48 +00:00
Quantity: bidQuantity,
2023-06-13 04:22:59 +00:00
Price: bidPrice,
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
})
}
if placeSell {
liqOrders = append(liqOrders, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimitMaker,
2023-06-14 07:16:48 +00:00
Quantity: askQuantity,
2023-06-13 04:22:59 +00:00
Price: askPrice,
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
})
}
}
2023-06-14 08:20:37 +00:00
makerQuota.Commit()
2023-06-13 04:22:59 +00:00
createdOrders, err := s.OrderExecutor.SubmitOrders(ctx, liqOrders...)
2023-06-14 08:20:37 +00:00
if logErr(err, "unable to place liquidity orders") {
return
2023-06-13 04:22:59 +00:00
}
2023-06-14 08:20:37 +00:00
s.liquidityOrderBook.Add(createdOrders...)
2023-07-03 08:22:01 +00:00
log.Infof("%d liq orders are placed successfully", len(liqOrders))
2023-06-14 08:20:37 +00:00
}
2023-06-13 04:22:59 +00:00
2023-06-14 08:20:37 +00:00
func profitProtectedPrice(side types.SideType, averageCost, price, feeRate, minProfit fixedpoint.Value) fixedpoint.Value {
switch side {
case types.SideTypeSell:
minProfitPrice := averageCost.Add(
averageCost.Mul(feeRate.Add(minProfit)))
return fixedpoint.Max(minProfitPrice, price)
2023-06-13 04:22:59 +00:00
2023-06-14 08:20:37 +00:00
case types.SideTypeBuy:
minProfitPrice := averageCost.Sub(
averageCost.Mul(feeRate.Add(minProfit)))
return fixedpoint.Min(minProfitPrice, price)
2023-06-13 04:22:59 +00:00
}
2023-06-14 08:20:37 +00:00
return price
2023-06-13 04:22:59 +00:00
}
func logErr(err error, msgAndArgs ...interface{}) bool {
if err == nil {
return false
}
if len(msgAndArgs) == 0 {
log.WithError(err).Error(err.Error())
} else if len(msgAndArgs) == 1 {
msg := msgAndArgs[0].(string)
log.WithError(err).Error(msg)
} else if len(msgAndArgs) > 1 {
msg := msgAndArgs[0].(string)
log.WithError(err).Errorf(msg, msgAndArgs[1:]...)
}
return true
}