bbgo_origin/pkg/strategy/xgap/strategy.go

377 lines
10 KiB
Go
Raw Normal View History

2021-12-26 07:13:51 +00:00
package xgap
2021-03-22 01:54:38 +00:00
import (
"context"
"fmt"
"math"
2022-01-14 03:59:40 +00:00
"math/rand"
2021-03-22 01:54:38 +00:00
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
2024-01-05 02:23:12 +00:00
"github.com/c9s/bbgo/pkg/strategy/common"
2021-03-22 01:54:38 +00:00
"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/util/timejitter"
2021-03-22 01:54:38 +00:00
)
2021-12-26 07:13:51 +00:00
const ID = "xgap"
2021-03-22 01:54:38 +00:00
var log = logrus.WithField("strategy", ID)
var maxStepPercentageGap = fixedpoint.NewFromFloat(0.05)
var Two = fixedpoint.NewFromInt(2)
2021-03-22 01:54:38 +00:00
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
func (s *Strategy) ID() string {
return ID
}
2024-01-05 02:23:12 +00:00
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
2021-03-22 01:54:38 +00:00
type Strategy struct {
2024-01-05 02:23:12 +00:00
*common.Strategy
*common.FeeBudget
2024-01-05 02:23:12 +00:00
Environment *bbgo.Environment
Symbol string `json:"symbol"`
SourceExchange string `json:"sourceExchange"`
TradingExchange string `json:"tradingExchange"`
2022-01-14 04:10:40 +00:00
MinSpread fixedpoint.Value `json:"minSpread"`
Quantity fixedpoint.Value `json:"quantity"`
DryRun bool `json:"dryRun"`
2021-03-22 01:54:38 +00:00
DailyMaxVolume fixedpoint.Value `json:"dailyMaxVolume,omitempty"`
DailyTargetVolume fixedpoint.Value `json:"dailyTargetVolume,omitempty"`
UpdateInterval types.Duration `json:"updateInterval"`
SimulateVolume bool `json:"simulateVolume"`
SimulatePrice bool `json:"simulatePrice"`
2021-03-22 01:54:38 +00:00
sourceSession, tradingSession *bbgo.ExchangeSession
sourceMarket, tradingMarket types.Market
2021-12-27 17:47:07 +00:00
mu sync.Mutex
lastSourceKLine, lastTradingKLine types.KLine
sourceBook, tradingBook *types.StreamOrderBook
2024-01-04 10:21:24 +00:00
2021-03-22 01:54:38 +00:00
stopC chan struct{}
}
2024-01-05 02:23:12 +00:00
func (s *Strategy) Initialize() error {
if s.Strategy == nil {
s.Strategy = &common.Strategy{}
}
if s.FeeBudget == nil {
s.FeeBudget = &common.FeeBudget{}
}
2024-01-05 02:23:12 +00:00
return nil
}
func (s *Strategy) Validate() error {
return nil
}
func (s *Strategy) Defaults() error {
if s.UpdateInterval == 0 {
s.UpdateInterval = types.Duration(time.Second)
}
return nil
}
2021-03-22 01:54:38 +00:00
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {
sourceSession, ok := sessions[s.SourceExchange]
if !ok {
panic(fmt.Errorf("source session %s is not defined", s.SourceExchange))
}
sourceSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
2024-03-13 15:18:39 +00:00
sourceSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{Depth: types.DepthLevel5})
2021-03-22 01:54:38 +00:00
tradingSession, ok := sessions[s.TradingExchange]
if !ok {
panic(fmt.Errorf("trading session %s is not defined", s.TradingExchange))
}
2021-12-27 18:14:49 +00:00
tradingSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
2024-03-13 15:18:39 +00:00
tradingSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{Depth: types.DepthLevel5})
2021-03-22 01:54:38 +00:00
}
2021-03-22 10:48:18 +00:00
func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error {
2021-03-22 01:54:38 +00:00
sourceSession, ok := sessions[s.SourceExchange]
if !ok {
return fmt.Errorf("source session %s is not defined", s.SourceExchange)
}
s.sourceSession = sourceSession
tradingSession, ok := sessions[s.TradingExchange]
if !ok {
return fmt.Errorf("trading session %s is not defined", s.TradingExchange)
}
s.tradingSession = tradingSession
s.sourceMarket, ok = s.sourceSession.Market(s.Symbol)
if !ok {
return fmt.Errorf("source session market %s is not defined", s.Symbol)
}
s.tradingMarket, ok = s.tradingSession.Market(s.Symbol)
if !ok {
return fmt.Errorf("trading session market %s is not defined", s.Symbol)
}
2024-01-05 02:23:12 +00:00
s.Strategy.Initialize(ctx, s.Environment, tradingSession, s.tradingMarket, ID, s.InstanceID())
s.FeeBudget.Initialize()
2024-01-05 02:23:12 +00:00
2021-03-22 09:26:53 +00:00
s.stopC = make(chan struct{})
2022-10-03 08:01:08 +00:00
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
2021-03-22 09:26:53 +00:00
defer wg.Done()
close(s.stopC)
2024-05-14 10:54:24 +00:00
bbgo.Sync(ctx, s)
2021-03-22 09:26:53 +00:00
})
2021-03-22 01:54:38 +00:00
// from here, set data binding
2021-05-27 19:13:50 +00:00
s.sourceSession.MarketDataStream.OnKLine(func(kline types.KLine) {
2021-03-22 01:54:38 +00:00
s.mu.Lock()
2021-12-27 17:47:07 +00:00
s.lastSourceKLine = kline
s.mu.Unlock()
})
s.tradingSession.MarketDataStream.OnKLine(func(kline types.KLine) {
s.mu.Lock()
s.lastTradingKLine = kline
2021-03-22 01:54:38 +00:00
s.mu.Unlock()
})
2024-06-13 07:40:32 +00:00
if s.SourceExchange != "" {
s.sourceBook = types.NewStreamBook(s.Symbol, sourceSession.ExchangeName)
2024-06-13 07:40:32 +00:00
s.sourceBook.BindStream(s.sourceSession.MarketDataStream)
}
2021-03-22 01:54:38 +00:00
s.tradingBook = types.NewStreamBook(s.Symbol, tradingSession.ExchangeName)
2021-05-27 19:13:50 +00:00
s.tradingBook.BindStream(s.tradingSession.MarketDataStream)
2021-03-22 01:54:38 +00:00
s.tradingSession.UserDataStream.OnTradeUpdate(func(trade types.Trade) {
if trade.Symbol != s.Symbol {
return
}
s.FeeBudget.HandleTradeUpdate(trade)
})
2021-03-22 09:26:53 +00:00
2021-03-22 01:54:38 +00:00
go func() {
2022-01-14 04:03:29 +00:00
ticker := time.NewTicker(
timejitter.Milliseconds(s.UpdateInterval.Duration(), 1000),
2022-01-14 04:03:29 +00:00
)
2021-03-22 01:54:38 +00:00
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
2021-03-22 09:26:53 +00:00
case <-s.stopC:
return
2021-03-22 01:54:38 +00:00
case <-ticker.C:
if !s.IsBudgetAllowed() {
2021-03-22 10:48:18 +00:00
continue
}
2022-01-14 04:03:29 +00:00
// < 10 seconds jitter sleep
delay := timejitter.Milliseconds(s.UpdateInterval.Duration(), 10*1000)
2022-01-14 04:03:29 +00:00
if delay < s.UpdateInterval.Duration() {
time.Sleep(delay)
}
2024-01-05 02:23:12 +00:00
s.placeOrders(ctx)
2021-03-22 01:54:38 +00:00
2024-01-05 02:23:12 +00:00
s.cancelOrders(ctx)
}
}
}()
2021-03-22 01:54:38 +00:00
2024-01-05 02:23:12 +00:00
return nil
}
2024-01-05 02:23:12 +00:00
func (s *Strategy) placeOrders(ctx context.Context) {
bestBid, hasBid := s.tradingBook.BestBid()
bestAsk, hasAsk := s.tradingBook.BestAsk()
// try to use the bid/ask price from the trading book
if hasBid && hasAsk {
var spread = bestAsk.Price.Sub(bestBid.Price)
var spreadPercentage = spread.Div(bestAsk.Price)
log.Infof("trading book spread=%s %s",
spread.String(), spreadPercentage.Percentage())
// use the source book price if the spread percentage greater than 5%
2024-06-13 07:40:32 +00:00
if s.SimulatePrice && s.sourceBook != nil && spreadPercentage.Compare(maxStepPercentageGap) > 0 {
2024-01-05 02:23:12 +00:00
log.Warnf("spread too large (%s %s), using source book",
spread.String(), spreadPercentage.Percentage())
bestBid, hasBid = s.sourceBook.BestBid()
bestAsk, hasAsk = s.sourceBook.BestAsk()
}
2021-03-22 01:54:38 +00:00
2024-01-05 02:23:12 +00:00
if s.MinSpread.Sign() > 0 {
if spread.Compare(s.MinSpread) < 0 {
log.Warnf("spread < min spread, spread=%s minSpread=%s bid=%s ask=%s",
spread.String(), s.MinSpread.String(),
bestBid.Price.String(), bestAsk.Price.String())
return
}
}
2021-03-22 01:54:38 +00:00
2024-01-05 02:23:12 +00:00
// if the spread is less than 100 ticks (100 pips), skip
if spread.Compare(s.tradingMarket.TickSize.MulExp(2)) < 0 {
2024-01-06 07:24:14 +00:00
log.Warnf("spread too small, we can't place orders: spread=%s bid=%s ask=%s",
spread.String(), bestBid.Price.String(), bestAsk.Price.String())
2024-01-05 02:23:12 +00:00
return
}
2024-01-04 10:21:24 +00:00
2024-06-13 07:40:32 +00:00
} else if s.sourceBook != nil {
2024-01-05 02:23:12 +00:00
bestBid, hasBid = s.sourceBook.BestBid()
bestAsk, hasAsk = s.sourceBook.BestAsk()
}
2021-03-22 01:54:38 +00:00
2024-01-05 02:23:12 +00:00
if !hasBid || !hasAsk {
log.Warn("no bids or asks on the source book or the trading book")
return
}
2024-06-13 07:55:40 +00:00
if bestBid.Price.IsZero() || bestAsk.Price.IsZero() {
log.Warn("bid price or ask price is zero")
return
}
2024-01-05 02:23:12 +00:00
var spread = bestAsk.Price.Sub(bestBid.Price)
var spreadPercentage = spread.Div(bestAsk.Price)
2024-06-13 07:55:40 +00:00
log.Infof("spread:%s %s ask:%s bid:%s",
2024-01-06 07:24:14 +00:00
spread.String(), spreadPercentage.Percentage(),
bestAsk.Price.String(), bestBid.Price.String())
2024-01-05 02:23:12 +00:00
// var spreadPercentage = spread.Float64() / bestBid.Price.Float64()
var midPrice = bestAsk.Price.Add(bestBid.Price).Div(Two)
var price = midPrice
2024-01-06 07:24:14 +00:00
log.Infof("mid price %s", midPrice.String())
2024-01-05 02:23:12 +00:00
var balances = s.tradingSession.GetAccount().Balances()
baseBalance, ok := balances[s.tradingMarket.BaseCurrency]
if !ok {
log.Errorf("base balance %s not found", s.tradingMarket.BaseCurrency)
return
}
2024-06-13 07:55:40 +00:00
quoteBalance, ok := balances[s.tradingMarket.QuoteCurrency]
if !ok {
log.Errorf("quote balance %s not found", s.tradingMarket.QuoteCurrency)
return
}
minQuantity := s.tradingMarket.AdjustQuantityByMinNotional(s.tradingMarket.MinQuantity, price)
if baseBalance.Available.Compare(minQuantity) <= 0 {
2024-01-07 10:56:57 +00:00
log.Infof("base balance: %s %s is not enough, skip", baseBalance.Available.String(), s.tradingMarket.BaseCurrency)
return
}
if quoteBalance.Available.Div(price).Compare(minQuantity) <= 0 {
2024-01-07 10:56:57 +00:00
log.Infof("quote balance: %s %s is not enough, skip", quoteBalance.Available.String(), s.tradingMarket.QuoteCurrency)
return
}
2024-06-13 07:55:40 +00:00
maxQuantity := baseBalance.Available
if !quoteBalance.Available.IsZero() {
maxQuantity = fixedpoint.Min(maxQuantity, quoteBalance.Available.Div(price))
}
quantity := minQuantity
2024-01-05 02:23:12 +00:00
2024-06-13 07:55:40 +00:00
// if we set the fixed quantity, we should use the fixed
2024-01-05 02:23:12 +00:00
if s.Quantity.Sign() > 0 {
quantity = fixedpoint.Max(s.Quantity, quantity)
2024-01-05 02:23:12 +00:00
} else if s.SimulateVolume {
s.mu.Lock()
if s.lastTradingKLine.Volume.Sign() > 0 && s.lastSourceKLine.Volume.Sign() > 0 {
2024-01-06 07:24:14 +00:00
log.Infof("trading exchange %s price: %s volume: %s",
s.Symbol, s.lastTradingKLine.Close.String(), s.lastTradingKLine.Volume.String())
log.Infof("source exchange %s price: %s volume: %s",
s.Symbol, s.lastSourceKLine.Close.String(), s.lastSourceKLine.Volume.String())
2024-01-05 02:23:12 +00:00
volumeDiff := s.lastSourceKLine.Volume.Sub(s.lastTradingKLine.Volume)
// change the current quantity only diff is positive
if volumeDiff.Sign() > 0 {
quantity = volumeDiff
}
2021-03-22 01:54:38 +00:00
}
2024-01-05 02:23:12 +00:00
s.mu.Unlock()
2024-06-18 08:49:47 +00:00
} else if s.DailyTargetVolume.Sign() > 0 {
numOfTicks := (24 * time.Hour) / s.UpdateInterval.Duration()
quantity = fixedpoint.NewFromFloat(s.DailyTargetVolume.Float64() / float64(numOfTicks))
quantity = quantityJitter(quantity, 0.02)
2024-01-05 02:23:12 +00:00
} else {
// plus a 2% quantity jitter
2024-06-18 08:49:47 +00:00
quantity = quantityJitter(quantity, 0.02)
2024-01-05 02:23:12 +00:00
}
2021-03-22 01:54:38 +00:00
2024-06-13 07:55:40 +00:00
log.Infof("%s quantity: %f", s.Symbol, quantity.Float64())
quantity = fixedpoint.Min(quantity, maxQuantity)
2024-06-13 07:55:40 +00:00
log.Infof("%s adjusted quantity: %f", s.Symbol, quantity.Float64())
orderForms := []types.SubmitOrder{
{
Symbol: s.Symbol,
Side: types.SideTypeBuy,
Type: types.OrderTypeLimit,
Quantity: quantity,
Price: price,
Market: s.tradingMarket,
},
{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimit,
Quantity: quantity,
Price: price,
Market: s.tradingMarket,
},
}
log.Infof("order forms: %+v", orderForms)
if s.DryRun {
log.Infof("dry run, skip")
return
2024-01-05 02:23:12 +00:00
}
_, err := s.OrderExecutor.SubmitOrders(ctx, orderForms...)
2024-01-05 02:23:12 +00:00
if err != nil {
log.WithError(err).Error("order submit error")
}
time.Sleep(time.Second)
}
func (s *Strategy) cancelOrders(ctx context.Context) {
if err := s.OrderExecutor.GracefulCancel(ctx); err != nil {
log.WithError(err).Error("cancel order error")
}
2021-03-22 01:54:38 +00:00
}
2024-06-18 08:49:47 +00:00
func quantityJitter(q fixedpoint.Value, rg float64) fixedpoint.Value {
jitter := 1.0 + math.Max(rg, rand.Float64())
return q.Mul(fixedpoint.NewFromFloat(jitter))
}