bbgo_origin/pkg/strategy/buyandhold/strategy.go

95 lines
2.2 KiB
Go
Raw Normal View History

package buyandhold
import (
"context"
2020-12-14 06:21:02 +00:00
"fmt"
"math"
2020-12-14 06:21:02 +00:00
"github.com/sirupsen/logrus"
2020-10-15 15:38:00 +00:00
"github.com/c9s/bbgo/pkg/bbgo"
2020-12-14 06:21:02 +00:00
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
2020-12-14 06:21:02 +00:00
var log = logrus.WithField("strategy", "buyandhold")
2020-10-20 05:52:25 +00:00
func init() {
2020-10-28 23:54:59 +00:00
bbgo.RegisterStrategy("buyandhold", &Strategy{})
2020-10-20 05:52:25 +00:00
}
type Strategy struct {
2020-12-14 06:21:02 +00:00
Symbol string `json:"symbol"`
Interval string `json:"interval"`
BaseQuantity float64 `json:"baseQuantity"`
MinDropPercentage fixedpoint.Value `json:"minDropPercentage"`
MinDropChange fixedpoint.Value `json:"minDropChange"`
}
2020-10-28 09:49:49 +00:00
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
2020-10-28 09:49:49 +00:00
}
2020-10-28 09:49:49 +00:00
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2020-12-14 06:21:02 +00:00
// buy when price drops -8%
market, ok := session.Market(s.Symbol)
if !ok {
return fmt.Errorf("market %s is not defined", s.Symbol)
}
session.Stream.OnKLine(func(kline types.KLine) {
// skip k-lines from other symbols
if kline.Symbol != s.Symbol {
return
}
changePercentage := kline.GetChange() / kline.Open
2020-12-14 06:21:02 +00:00
log.Infof("change %f <=> %f", changePercentage, s.MinDropPercentage.Float64())
})
session.Stream.OnKLineClosed(func(kline types.KLine) {
// skip k-lines from other symbols
if kline.Symbol != s.Symbol {
return
}
2020-12-14 06:21:02 +00:00
change := kline.GetChange()
2020-12-14 06:21:02 +00:00
// skip positive change
if change > 0 {
return
}
2020-12-14 06:21:02 +00:00
changeP := change / kline.Open
if s.MinDropPercentage != 0 {
if math.Abs(changeP) < math.Abs(s.MinDropPercentage.Float64()) {
return
}
} else if s.MinDropChange != 0 {
if math.Abs(change) < math.Abs(s.MinDropChange.Float64()) {
return
}
} else {
// not configured, we shall skip
log.Warnf("parameters are not configured, skipping action...")
return
}
2020-12-14 06:21:02 +00:00
quantity := s.BaseQuantity * (1.0 + math.Abs(changeP))
_, err := orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: kline.Symbol,
Market: market,
Side: types.SideTypeBuy,
Type: types.OrderTypeMarket,
2020-10-28 01:43:19 +00:00
Quantity: quantity,
})
if err != nil {
log.WithError(err).Error("submit order error")
}
})
return nil
}