bbgo_origin/pkg/strategy/xgap/strategy.go

369 lines
11 KiB
Go
Raw Permalink 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"
"github.com/c9s/bbgo/pkg/types"
2022-01-14 04:03:29 +00:00
"github.com/c9s/bbgo/pkg/util"
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
const stateKey = "state-v1"
var log = logrus.WithField("strategy", ID)
var StepPercentageGap = fixedpoint.NewFromFloat(0.05)
var NotionModifier = fixedpoint.NewFromFloat(1.01)
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
}
2021-03-22 07:50:47 +00:00
type State struct {
2021-03-22 10:48:18 +00:00
AccumulatedFeeStartedAt time.Time `json:"accumulatedFeeStartedAt,omitempty"`
AccumulatedFees map[string]fixedpoint.Value `json:"accumulatedFees,omitempty"`
AccumulatedVolume fixedpoint.Value `json:"accumulatedVolume,omitempty"`
}
func (s *State) IsOver24Hours() bool {
2022-06-17 11:19:51 +00:00
return time.Since(s.AccumulatedFeeStartedAt) >= 24*time.Hour
2021-03-22 10:48:18 +00:00
}
func (s *State) Reset() {
t := time.Now()
dateTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
log.Infof("resetting accumulated started time to: %s", dateTime)
s.AccumulatedFeeStartedAt = dateTime
s.AccumulatedFees = make(map[string]fixedpoint.Value)
s.AccumulatedVolume = fixedpoint.Zero
2021-03-22 07:50:47 +00:00
}
2021-03-22 01:54:38 +00:00
type Strategy struct {
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"`
2021-03-22 01:54:38 +00:00
2021-03-22 10:48:18 +00:00
DailyFeeBudgets map[string]fixedpoint.Value `json:"dailyFeeBudgets,omitempty"`
DailyMaxVolume fixedpoint.Value `json:"dailyMaxVolume,omitempty"`
UpdateInterval types.Duration `json:"updateInterval"`
2021-12-27 17:47:07 +00:00
SimulateVolume bool `json:"simulateVolume"`
2021-03-22 01:54:38 +00:00
sourceSession, tradingSession *bbgo.ExchangeSession
sourceMarket, tradingMarket types.Market
2022-10-03 10:37:53 +00:00
State *State `persistence:"state"`
2021-03-22 01:54:38 +00:00
2021-12-27 17:47:07 +00:00
mu sync.Mutex
lastSourceKLine, lastTradingKLine types.KLine
sourceBook, tradingBook *types.StreamOrderBook
groupID uint32
2021-03-22 01:54:38 +00:00
stopC chan struct{}
}
2021-03-22 10:48:18 +00:00
func (s *Strategy) isBudgetAllowed() bool {
if s.DailyFeeBudgets == nil {
return true
}
2022-10-03 10:37:53 +00:00
if s.State.AccumulatedFees == nil {
2021-03-22 10:48:18 +00:00
return true
}
for asset, budget := range s.DailyFeeBudgets {
2022-10-03 10:37:53 +00:00
if fee, ok := s.State.AccumulatedFees[asset]; ok {
if fee.Compare(budget) >= 0 {
log.Warnf("accumulative fee %s exceeded the fee budget %s, skipping...", fee.String(), budget.String())
2021-03-22 10:48:18 +00:00
return false
}
}
}
return true
}
2021-03-22 01:54:38 +00:00
func (s *Strategy) handleTradeUpdate(trade types.Trade) {
log.Infof("received trade %+v", trade)
if trade.Symbol != s.Symbol {
return
}
2021-03-22 07:50:47 +00:00
2022-10-03 10:37:53 +00:00
if s.State.IsOver24Hours() {
s.State.Reset()
2021-03-22 07:50:47 +00:00
}
2021-03-22 10:48:18 +00:00
// safe check
2022-10-03 10:37:53 +00:00
if s.State.AccumulatedFees == nil {
s.State.AccumulatedFees = make(map[string]fixedpoint.Value)
2021-03-22 10:48:18 +00:00
}
2021-03-22 07:50:47 +00:00
2022-10-03 10:37:53 +00:00
s.State.AccumulatedFees[trade.FeeCurrency] = s.State.AccumulatedFees[trade.FeeCurrency].Add(trade.Fee)
s.State.AccumulatedVolume = s.State.AccumulatedVolume.Add(trade.Quantity)
log.Infof("accumulated fee: %s %s", s.State.AccumulatedFees[trade.FeeCurrency].String(), trade.FeeCurrency)
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"})
2022-01-19 05:08:50 +00:00
sourceSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{})
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"})
2022-01-19 05:08:50 +00:00
tradingSession.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{})
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
if s.UpdateInterval == 0 {
s.UpdateInterval = types.Duration(time.Second)
}
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)
}
2021-03-22 09:26:53 +00:00
s.stopC = make(chan struct{})
2022-10-03 10:37:53 +00:00
if s.State == nil {
s.State = &State{}
s.State.Reset()
}
2021-03-22 10:48:18 +00:00
2022-10-03 10:37:53 +00:00
if s.State.IsOver24Hours() {
log.Warn("state is over 24 hours, resetting to zero")
s.State.Reset()
2021-03-22 09:26:53 +00:00
}
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)
2022-10-03 10:45:24 +00:00
bbgo.Sync(context.Background(), 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) {
log.Infof("source exchange %s price: %s volume: %s",
s.Symbol, kline.Close.String(), kline.Volume.String())
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) {
log.Infof("trading exchange %s price: %s volume: %s",
s.Symbol, kline.Close.String(), kline.Volume.String())
2021-12-27 17:47:07 +00:00
s.mu.Lock()
s.lastTradingKLine = kline
2021-03-22 01:54:38 +00:00
s.mu.Unlock()
})
s.sourceBook = types.NewStreamBook(s.Symbol)
2021-05-27 19:13:50 +00:00
s.sourceBook.BindStream(s.sourceSession.MarketDataStream)
2021-03-22 01:54:38 +00:00
s.tradingBook = types.NewStreamBook(s.Symbol)
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(s.handleTradeUpdate)
2021-03-22 09:26:53 +00:00
2021-03-22 01:54:38 +00:00
instanceID := fmt.Sprintf("%s-%s", ID, s.Symbol)
s.groupID = util.FNV32(instanceID)
2021-03-22 01:54:38 +00:00
log.Infof("using group id %d from fnv32(%s)", s.groupID, instanceID)
go func() {
2022-01-14 04:03:29 +00:00
ticker := time.NewTicker(
util.MillisecondsJitter(s.UpdateInterval.Duration(), 1000),
)
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:
2021-03-22 10:48:18 +00:00
if !s.isBudgetAllowed() {
continue
}
2022-01-14 04:03:29 +00:00
// < 10 seconds jitter sleep
delay := util.MillisecondsJitter(s.UpdateInterval.Duration(), 10*1000)
if delay < s.UpdateInterval.Duration() {
time.Sleep(delay)
}
bestBid, hasBid := s.tradingBook.BestBid()
bestAsk, hasAsk := s.tradingBook.BestAsk()
2021-03-22 01:54:38 +00:00
// 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())
2021-03-22 01:54:38 +00:00
// use the source book price if the spread percentage greater than 10%
if spreadPercentage.Compare(StepPercentageGap) > 0 {
log.Warnf("spread too large (%s %s), using source book",
spread.String(), spreadPercentage.Percentage())
2022-01-14 04:03:29 +00:00
bestBid, hasBid = s.sourceBook.BestBid()
bestAsk, hasAsk = s.sourceBook.BestAsk()
2021-03-22 01:54:38 +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())
2022-01-14 04:10:40 +00:00
continue
}
}
2021-03-22 10:48:18 +00:00
// if the spread is less than 100 ticks (100 pips), skip
if spread.Compare(s.tradingMarket.TickSize.MulExp(2)) < 0 {
log.Warnf("spread too small, we can't place orders: spread=%v bid=%v ask=%v",
spread, bestBid.Price, bestAsk.Price)
2021-03-22 01:54:38 +00:00
continue
}
} else {
2022-01-14 04:03:29 +00:00
bestBid, hasBid = s.sourceBook.BestBid()
bestAsk, hasAsk = s.sourceBook.BestAsk()
2021-03-22 01:54:38 +00:00
}
if !hasBid || !hasAsk {
log.Warn("no bids or asks on the source book or the trading book")
continue
}
var spread = bestAsk.Price.Sub(bestBid.Price)
var spreadPercentage = spread.Div(bestAsk.Price)
log.Infof("spread=%v %s ask=%v bid=%v",
spread, spreadPercentage.Percentage(),
bestAsk.Price, bestBid.Price)
2021-03-22 01:54:38 +00:00
// var spreadPercentage = spread.Float64() / bestBid.Price.Float64()
var midPrice = bestAsk.Price.Add(bestBid.Price).Div(Two)
var price = midPrice
2021-03-22 01:54:38 +00:00
log.Infof("mid price %v", midPrice)
2021-03-22 01:54:38 +00:00
var balances = s.tradingSession.GetAccount().Balances()
2021-03-22 01:54:38 +00:00
var quantity = s.tradingMarket.MinQuantity
if s.Quantity.Sign() > 0 {
quantity = fixedpoint.Min(s.Quantity, s.tradingMarket.MinQuantity)
2021-12-27 17:47:07 +00:00
} else if s.SimulateVolume {
s.mu.Lock()
if s.lastTradingKLine.Volume.Sign() > 0 && s.lastSourceKLine.Volume.Sign() > 0 {
volumeDiff := s.lastSourceKLine.Volume.Sub(s.lastTradingKLine.Volume)
2021-12-27 17:47:07 +00:00
// change the current quantity only diff is positive
if volumeDiff.Sign() > 0 {
2021-12-27 17:47:07 +00:00
quantity = volumeDiff
}
if baseBalance, ok := balances[s.tradingMarket.BaseCurrency]; ok {
quantity = fixedpoint.Min(quantity, baseBalance.Available)
}
if quoteBalance, ok := balances[s.tradingMarket.QuoteCurrency]; ok {
maxQuantity := quoteBalance.Available.Div(price)
quantity = fixedpoint.Min(quantity, maxQuantity)
}
2021-12-27 17:47:07 +00:00
}
s.mu.Unlock()
2022-01-14 03:59:40 +00:00
} else {
// plus a 2% quantity jitter
jitter := 1.0 + math.Max(0.02, rand.Float64())
quantity = quantity.Mul(fixedpoint.NewFromFloat(jitter))
}
var quoteAmount = price.Mul(quantity)
if quoteAmount.Compare(s.tradingMarket.MinNotional) <= 0 {
quantity = fixedpoint.Max(
2021-03-22 01:54:38 +00:00
s.tradingMarket.MinQuantity,
s.tradingMarket.MinNotional.Mul(NotionModifier).Div(price))
2021-03-22 01:54:38 +00:00
}
createdOrders, _, err := bbgo.BatchPlaceOrder(ctx, tradingSession.Exchange, nil, types.SubmitOrder{
2021-12-27 17:47:07 +00:00
Symbol: s.Symbol,
Side: types.SideTypeBuy,
Type: types.OrderTypeLimit,
Quantity: quantity,
Price: price,
Market: s.tradingMarket,
2022-02-18 05:52:13 +00:00
// TimeInForce: types.TimeInForceGTC,
2021-12-27 17:47:07 +00:00
GroupID: s.groupID,
2021-03-22 01:54:38 +00:00
}, types.SubmitOrder{
2021-12-27 17:47:07 +00:00
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimit,
Quantity: quantity,
Price: price,
Market: s.tradingMarket,
2022-02-18 05:52:13 +00:00
// TimeInForce: types.TimeInForceGTC,
2021-12-27 17:47:07 +00:00
GroupID: s.groupID,
2021-03-22 01:54:38 +00:00
})
2021-03-22 01:54:38 +00:00
if err != nil {
log.WithError(err).Error("order submit error")
}
time.Sleep(time.Second)
if err := tradingSession.Exchange.CancelOrders(ctx, createdOrders...); err != nil {
log.WithError(err).Error("cancel order error")
}
}
}
}()
return nil
}