bbgo_origin/pkg/strategy/support/strategy.go

384 lines
11 KiB
Go
Raw Normal View History

2021-02-14 17:26:46 +00:00
package support
2021-02-10 16:21:06 +00:00
import (
"context"
"fmt"
2021-05-30 17:02:35 +00:00
"sync"
2021-02-10 16:21:06 +00:00
2021-05-30 17:02:35 +00:00
"github.com/c9s/bbgo/pkg/service"
2021-02-10 16:21:06 +00:00
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
2021-02-14 17:26:46 +00:00
const ID = "support"
2021-02-10 16:21:06 +00:00
2021-05-30 17:02:35 +00:00
const stateKey = "state-v1"
2021-02-10 16:21:06 +00:00
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
2021-05-30 17:02:35 +00:00
type State struct {
Position *bbgo.Position `json:"position,omitempty"`
}
2021-02-10 16:21:06 +00:00
type Target struct {
2021-02-14 17:26:46 +00:00
ProfitPercentage float64 `json:"profitPercentage"`
QuantityPercentage float64 `json:"quantityPercentage"`
MarginOrderSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
2021-02-10 16:21:06 +00:00
}
type Strategy struct {
2021-02-20 02:50:57 +00:00
*bbgo.Notifiability
2021-05-30 17:02:35 +00:00
*bbgo.Persistence
*bbgo.Graceful
2021-02-20 02:50:57 +00:00
2021-02-14 17:26:46 +00:00
Symbol string `json:"symbol"`
Interval types.Interval `json:"interval"`
MovingAverageWindow int `json:"movingAverageWindow"`
Quantity fixedpoint.Value `json:"quantity"`
MinVolume fixedpoint.Value `json:"minVolume"`
2021-06-16 05:14:10 +00:00
Sensitivity fixedpoint.Value `json:"sensitivity"`
TakerBuyRatio fixedpoint.Value `json:"takerBuyRatio"`
2021-02-14 17:26:46 +00:00
MarginOrderSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
Targets []Target `json:"targets"`
2021-06-16 05:23:33 +00:00
ResistanceSensitivity fixedpoint.Value `json:"resistanceSensitivity"`
ResistanceMinVolume fixedpoint.Value `json:"resistanceMinVolume"`
ResistanceTakerBuyRatio fixedpoint.Value `json:"resistanceTakerBuyRatio"`
// Max BaseAsset balance to buy
MaxBaseAssetBalance fixedpoint.Value `json:"maxBaseAssetBalance"`
MinQuoteAssetBalance fixedpoint.Value `json:"minQuoteAssetBalance"`
ScaleQuantity *bbgo.PriceVolumeScale `json:"scaleQuantity"`
orderStore *bbgo.OrderStore
tradeStore *bbgo.TradeStore
tradeC chan types.Trade
2021-05-30 17:02:35 +00:00
state *State
2021-02-10 16:21:06 +00:00
}
func (s *Strategy) ID() string {
return ID
}
2021-04-02 02:32:24 +00:00
func (s *Strategy) Validate() error {
if s.Quantity == 0 && s.ScaleQuantity == nil {
return fmt.Errorf("quantity or scaleQuantity can not be zero")
}
2021-06-16 05:14:10 +00:00
if s.MinVolume == 0 && s.Sensitivity == 0 {
return fmt.Errorf("either minVolume nor sensitivity can not be zero")
2021-04-02 02:32:24 +00:00
}
return nil
}
2021-02-10 16:21:06 +00:00
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: string(s.Interval)})
}
func (s *Strategy) handleTradeUpdate(trade types.Trade) {
s.tradeC <- trade
}
func (s *Strategy) tradeCollector(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case trade := <-s.tradeC:
s.tradeStore.Add(trade)
}
}
}
2021-05-30 17:02:35 +00:00
func (s *Strategy) SaveState() error {
if err := s.Persistence.Save(s.state, ID, s.Symbol, stateKey); err != nil {
return err
} else {
log.Infof("state is saved => %+v", s.state)
}
return nil
}
func (s *Strategy) LoadState() error {
var state State
// load position
if err := s.Persistence.Load(&state, ID, s.Symbol, stateKey); err != nil {
if err != service.ErrPersistenceNotExists {
return err
}
s.state = &State{}
} else {
s.state = &state
log.Infof("state is restored: %+v", s.state)
}
return nil
}
2021-02-10 16:21:06 +00:00
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
// buffer 100 trades in the channel
s.tradeC = make(chan types.Trade, 100)
s.tradeStore = bbgo.NewTradeStore(s.Symbol)
2021-02-10 16:21:06 +00:00
// set default values
if s.Interval == "" {
s.Interval = types.Interval5m
}
if s.MovingAverageWindow == 0 {
s.MovingAverageWindow = 99
}
2021-06-16 05:14:10 +00:00
if s.Sensitivity > 0 {
volRange, err := s.ScaleQuantity.ByVolumeRule.Range()
if err != nil {
return err
}
2021-06-16 06:16:39 +00:00
s.MinVolume = fixedpoint.NewFromFloat(volRange[0]) + fixedpoint.NewFromFloat(volRange[1] - volRange[0]).Mul(fixedpoint.NewFromFloat(1.0) - s.Sensitivity)
2021-06-16 05:23:33 +00:00
log.Infof("adjusted minimal support volume to %f according to sensitivity %f", s.MinVolume.Float64(), s.Sensitivity.Float64())
}
if s.ResistanceTakerBuyRatio == 0 {
s.ResistanceTakerBuyRatio = fixedpoint.NewFromFloat(0.5)
}
if s.ResistanceSensitivity > 0 {
volRange, err := s.ScaleQuantity.ByVolumeRule.Range()
if err != nil {
return err
}
2021-06-16 06:16:39 +00:00
s.ResistanceMinVolume = fixedpoint.NewFromFloat(volRange[0]) + fixedpoint.NewFromFloat(volRange[1] - volRange[0]).Mul(fixedpoint.NewFromFloat(1.0) - s.ResistanceSensitivity)
2021-06-16 05:23:33 +00:00
log.Infof("adjusted minimal resistance volume to %f according to sensitivity %f", s.ResistanceMinVolume.Float64(), s.ResistanceSensitivity.Float64())
2021-06-16 05:14:10 +00:00
}
2021-02-10 16:21:06 +00:00
market, ok := session.Market(s.Symbol)
if !ok {
return fmt.Errorf("market %s is not defined", s.Symbol)
}
standardIndicatorSet, ok := session.StandardIndicatorSet(s.Symbol)
if !ok {
return fmt.Errorf("standardIndicatorSet is nil, symbol %s", s.Symbol)
}
s.orderStore = bbgo.NewOrderStore(s.Symbol)
s.orderStore.BindStream(session.UserDataStream)
2021-02-10 16:21:06 +00:00
var iw = types.IntervalWindow{Interval: s.Interval, Window: s.MovingAverageWindow}
var ema = standardIndicatorSet.EWMA(iw)
2021-05-30 17:02:35 +00:00
if err := s.LoadState(); err != nil {
return err
} else {
s.Notify("%s state is restored => %+v", s.Symbol, s.state)
}
// init state
if s.state.Position == nil {
s.state.Position = &bbgo.Position{
Symbol: s.Symbol,
BaseCurrency: market.BaseCurrency,
QuoteCurrency: market.QuoteCurrency,
}
}
go s.tradeCollector(ctx)
session.UserDataStream.OnTradeUpdate(s.handleTradeUpdate)
2021-05-27 19:15:29 +00:00
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
2021-02-10 16:21:06 +00:00
// skip k-lines from other symbols
if kline.Symbol != s.Symbol {
return
}
closePriceF := kline.GetClose()
2021-06-16 05:23:33 +00:00
closePrice := fixedpoint.NewFromFloat(closePriceF)
// if it's above the EMA, it's resistance
if closePriceF > ema.Last() {
2021-06-16 05:23:33 +00:00
// check resistance volume
if kline.Volume < s.ResistanceMinVolume.Float64() {
return
}
takerBuyBaseVolumeThreshold := kline.Volume * s.ResistanceTakerBuyRatio.Float64()
if kline.TakerBuyBaseAssetVolume < takerBuyBaseVolumeThreshold {
2021-06-16 06:16:39 +00:00
s.Notify("%s: resistance detected, taker buy base volume %f < threshold %f (volume %f) at price %f",
2021-06-16 05:23:33 +00:00
s.Symbol,
kline.TakerBuyBaseAssetVolume,
takerBuyBaseVolumeThreshold,
kline.Volume,
closePriceF,
)
return
}
2021-02-10 16:21:06 +00:00
return
}
2021-06-16 05:23:33 +00:00
// check support
2021-02-10 16:21:06 +00:00
if kline.Volume < s.MinVolume.Float64() {
return
}
if s.TakerBuyRatio > 0 {
takerBuyBaseVolumeThreshold := kline.Volume * s.TakerBuyRatio.Float64()
if kline.TakerBuyBaseAssetVolume < takerBuyBaseVolumeThreshold {
2021-06-16 05:23:33 +00:00
s.Notify("%s: taker buy base volume %f is less than threshold %f (volume %f volume ratio %f)",
s.Symbol,
kline.TakerBuyBaseAssetVolume,
takerBuyBaseVolumeThreshold,
2021-06-16 05:23:33 +00:00
kline.Volume,
s.TakerBuyRatio.Float64(),
)
2021-06-01 08:39:35 +00:00
return
}
}
s.Notify("Found %s support: the close price %f is under EMA %f and volume %f > minimum volume %f",
s.Symbol,
closePrice.Float64(),
ema.Last(),
kline.Volume,
2021-05-30 17:02:35 +00:00
s.MinVolume.Float64(),
kline)
2021-02-10 16:21:06 +00:00
var quantity fixedpoint.Value
if s.Quantity > 0 {
quantity = s.Quantity
} else if s.ScaleQuantity != nil {
qf, err := s.ScaleQuantity.Scale(closePrice.Float64(), kline.Volume)
if err != nil {
log.WithError(err).Error(err.Error())
return
}
quantity = fixedpoint.NewFromFloat(qf)
}
2021-02-14 17:26:46 +00:00
baseBalance, _ := session.Account.Balance(market.BaseCurrency)
if s.MaxBaseAssetBalance > 0 && baseBalance.Total()+quantity > s.MaxBaseAssetBalance {
quota := s.MaxBaseAssetBalance - baseBalance.Total()
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, closePrice, quota)
}
quoteBalance, ok := session.Account.Balance(market.QuoteCurrency)
if !ok {
log.Errorf("quote balance %s not found", market.QuoteCurrency)
return
}
// for spot, we need to modify the quantity according to the quote balance
if !session.Margin {
// add 0.3% for price slippage
notional := closePrice.Mul(quantity).MulFloat64(1.003)
if s.MinQuoteAssetBalance > 0 && quoteBalance.Available-notional < s.MinQuoteAssetBalance {
log.Warnf("modifying quantity %f according to the min quote asset balance %f %s",
quantity.Float64(),
quoteBalance.Available.Float64(),
market.QuoteCurrency)
quota := quoteBalance.Available - s.MinQuoteAssetBalance
quantity = bbgo.AdjustQuantityByMinAmount(quantity, closePrice, quota)
} else if notional > quoteBalance.Available {
log.Warnf("modifying quantity %f according to the quote asset balance %f %s",
quantity.Float64(),
quoteBalance.Available.Float64(),
market.QuoteCurrency)
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, closePrice, quoteBalance.Available)
}
}
s.Notify("Submitting %s market order buy with quantity %f according to the base volume %f, taker buy base volume %f",
s.Symbol,
2021-06-01 08:39:35 +00:00
quantity.Float64(),
kline.Volume,
kline.TakerBuyBaseAssetVolume)
2021-02-14 17:26:46 +00:00
orderForm := types.SubmitOrder{
Symbol: s.Symbol,
Market: market,
Side: types.SideTypeBuy,
Type: types.OrderTypeMarket,
Quantity: quantity.Float64(),
2021-02-14 17:26:46 +00:00
MarginSideEffect: s.MarginOrderSideEffect,
}
createdOrders, err := orderExecutor.SubmitOrders(ctx, orderForm)
2021-02-10 16:21:06 +00:00
if err != nil {
log.WithError(err).Error("submit order error")
return
}
s.orderStore.Add(createdOrders...)
2021-02-10 16:21:06 +00:00
2021-05-30 17:02:35 +00:00
trades := s.tradeStore.GetAndClear()
for _, trade := range trades {
if s.orderStore.Exists(trade.OrderID) {
s.Notify(trade)
s.state.Position.AddTrade(trade)
}
}
s.Notify(s.state.Position)
2021-02-10 16:21:06 +00:00
// submit target orders
var targetOrders []types.SubmitOrder
for _, target := range s.Targets {
targetPrice := closePrice.Float64() * (1.0 + target.ProfitPercentage)
targetQuantity := quantity.Float64() * target.QuantityPercentage
targetQuoteQuantity := targetPrice * targetQuantity
if targetQuoteQuantity <= market.MinNotional {
continue
}
if targetQuantity <= market.MinQuantity {
continue
}
2021-02-10 16:21:06 +00:00
targetOrders = append(targetOrders, types.SubmitOrder{
Symbol: kline.Symbol,
Market: market,
Type: types.OrderTypeLimit,
Side: types.SideTypeSell,
Price: targetPrice,
Quantity: targetQuantity,
2021-02-14 17:26:46 +00:00
MarginSideEffect: target.MarginOrderSideEffect,
2021-02-10 16:21:06 +00:00
TimeInForce: "GTC",
})
}
createdOrders, err = orderExecutor.SubmitOrders(ctx, targetOrders...)
2021-02-10 16:21:06 +00:00
if err != nil {
log.WithError(err).Error("submit profit target order error")
}
s.orderStore.Add(createdOrders...)
2021-02-10 16:21:06 +00:00
})
2021-05-30 17:02:35 +00:00
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
if err := s.SaveState(); err != nil {
log.WithError(err).Errorf("can not save state: %+v", s.state)
} else {
s.Notify("%s position is saved", s.Symbol, s.state.Position)
}
})
2021-02-10 16:21:06 +00:00
return nil
}