bbgo_origin/pkg/strategy/skeleton/strategy.go

80 lines
1.7 KiB
Go
Raw Normal View History

2020-10-24 09:58:45 +00:00
package skeleton
import (
"context"
"github.com/sirupsen/logrus"
2020-10-24 09:58:45 +00:00
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
2020-10-24 09:58:45 +00:00
)
2021-02-03 01:08:05 +00:00
const ID = "skeleton"
var log = logrus.WithField("strategy", ID)
2021-02-03 01:08:05 +00:00
2020-10-24 09:58:45 +00:00
func init() {
2021-02-03 01:08:05 +00:00
bbgo.RegisterStrategy(ID, &Strategy{})
2020-10-24 09:58:45 +00:00
}
type Strategy struct {
Symbol string `json:"symbol"`
}
2021-02-03 01:08:05 +00:00
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
log.Infof("subscribe %s", s.Symbol)
2020-10-24 09:58:45 +00:00
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
}
2020-10-24 09:58:45 +00:00
var Ten = fixedpoint.NewFromInt(10)
// This strategy simply spent all available quote currency to buy the symbol whenever kline gets closed
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
market, ok := session.Market(s.Symbol)
if !ok {
log.Warnf("fetch market fail %s", s.Symbol)
return nil
}
callback := func(kline types.KLine) {
quoteBalance, ok := session.Account.Balance(market.QuoteCurrency)
if !ok {
return
}
quantityAmount := quoteBalance.Available
if quantityAmount.Sign() <= 0 || quantityAmount.Compare(Ten) < 0 {
return
}
currentPrice, ok := session.LastPrice(s.Symbol)
2020-10-24 09:58:45 +00:00
if !ok {
return
}
totalQuantity := quantityAmount.Div(currentPrice)
2020-10-24 09:58:45 +00:00
_, err := orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
2020-10-24 09:58:45 +00:00
Symbol: kline.Symbol,
Side: types.SideTypeBuy,
Type: types.OrderTypeMarket,
Price: currentPrice,
Quantity: totalQuantity,
2020-10-24 09:58:45 +00:00
})
if err != nil {
log.WithError(err).Error("submit order error")
}
}
session.UserDataStream.OnStart(func() {
log.Infof("connected")
2020-10-24 09:58:45 +00:00
})
session.MarketDataStream.OnKLineClosed(callback)
2020-10-24 09:58:45 +00:00
return nil
}