bbgo_origin/pkg/strategy/random/strategy.go

160 lines
3.6 KiB
Go
Raw Permalink Normal View History

2023-10-11 07:50:44 +00:00
package random
2023-10-04 18:19:09 +00:00
import (
"context"
"fmt"
"math/rand"
"sync"
"github.com/robfig/cron/v3"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/strategy/common"
"github.com/c9s/bbgo/pkg/types"
)
2023-10-11 07:50:44 +00:00
const ID = "random"
2023-10-04 18:19:09 +00:00
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
*common.Strategy
2023-10-04 18:19:09 +00:00
Environment *bbgo.Environment
Market types.Market
2023-10-13 10:11:21 +00:00
Symbol string `json:"symbol"`
CronExpression string `json:"cronExpression"`
OnStart bool `json:"onStart"`
DryRun bool `json:"dryRun"`
2023-10-07 05:01:45 +00:00
2023-10-13 10:11:21 +00:00
bbgo.QuantityOrAmount
2023-10-07 05:01:45 +00:00
cron *cron.Cron
2023-10-04 18:19:09 +00:00
}
func (s *Strategy) Defaults() error {
return nil
}
func (s *Strategy) Initialize() error {
s.Strategy = &common.Strategy{}
2023-10-04 18:19:09 +00:00
return nil
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
func (s *Strategy) Validate() error {
if s.CronExpression == "" {
return fmt.Errorf("cronExpression is required")
}
2023-10-13 10:11:21 +00:00
if err := s.QuantityOrAmount.Validate(); err != nil {
return err
}
2023-10-04 18:19:09 +00:00
return nil
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {}
func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
s.Strategy.Initialize(ctx, s.Environment, session, s.Market, s.ID(), s.InstanceID())
session.UserDataStream.OnStart(func() {
if s.OnStart {
2023-10-07 05:01:45 +00:00
s.placeOrder()
2023-10-04 18:19:09 +00:00
}
})
// the shutdown handler, you can cancel all orders
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
_ = s.OrderExecutor.GracefulCancel(ctx)
})
2023-10-07 05:01:45 +00:00
s.cron = cron.New()
s.cron.AddFunc(s.CronExpression, s.placeOrder)
s.cron.Start()
2023-10-04 18:19:09 +00:00
return nil
}
2023-10-07 05:01:45 +00:00
func (s *Strategy) placeOrder() {
ctx := context.Background()
baseBalance, ok := s.Session.GetAccount().Balance(s.Market.BaseCurrency)
if !ok {
log.Errorf("base balance not found")
return
}
quoteBalance, ok := s.Session.GetAccount().Balance(s.Market.QuoteCurrency)
if !ok {
log.Errorf("quote balance not found")
return
}
ticker, err := s.Session.Exchange.QueryTicker(ctx, s.Symbol)
if err != nil {
log.WithError(err).Error("query ticker error")
return
}
2023-10-13 10:11:21 +00:00
sellQuantity := s.CalculateQuantity(ticker.Sell)
buyQuantity := s.CalculateQuantity(ticker.Buy)
sellQuantity = s.Market.AdjustQuantityByMinNotional(sellQuantity, ticker.Sell)
buyQuantity = s.Market.AdjustQuantityByMinNotional(buyQuantity, ticker.Buy)
2023-10-07 05:01:45 +00:00
orderForm := []types.SubmitOrder{}
if baseBalance.Available.Compare(sellQuantity) > 0 {
orderForm = append(orderForm, types.SubmitOrder{
2023-10-04 18:19:09 +00:00
Symbol: s.Symbol,
2023-10-07 05:01:45 +00:00
Side: types.SideTypeSell,
2023-10-04 18:19:09 +00:00
Type: types.OrderTypeMarket,
2023-10-07 05:01:45 +00:00
Quantity: sellQuantity,
})
} else {
log.Infof("base balance: %s is not enough", baseBalance.Available.String())
}
if quoteBalance.Available.Div(ticker.Buy).Compare(buyQuantity) > 0 {
orderForm = append(orderForm, types.SubmitOrder{
2023-10-04 18:19:09 +00:00
Symbol: s.Symbol,
2023-10-07 05:01:45 +00:00
Side: types.SideTypeBuy,
2023-10-04 18:19:09 +00:00
Type: types.OrderTypeMarket,
2023-10-07 05:01:45 +00:00
Quantity: buyQuantity,
})
} else {
log.Infof("quote balance: %s is not enough", quoteBalance.Available.String())
2023-10-04 18:19:09 +00:00
}
2023-10-07 05:01:45 +00:00
var order types.SubmitOrder
if len(orderForm) == 0 {
log.Infof("both base and quote balance are not enough, skip submit order")
return
} else {
order = orderForm[rand.Intn(len(orderForm))]
}
log.Infof("submit order: %s", order.String())
2023-10-04 18:19:09 +00:00
if s.DryRun {
log.Infof("dry run, skip submit order")
return
}
2023-10-07 05:01:45 +00:00
_, err = s.OrderExecutor.SubmitOrders(ctx, order)
2023-10-04 18:19:09 +00:00
if err != nil {
log.WithError(err).Error("submit order error")
return
}
}