grid2: improve the onStart handler

This commit is contained in:
c9s 2023-03-03 18:22:31 +08:00
parent 0d41f0261a
commit fa395b0d0a
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54

View File

@ -1740,29 +1740,26 @@ func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.
// if TriggerPrice is zero, that means we need to open the grid when start up // if TriggerPrice is zero, that means we need to open the grid when start up
if s.TriggerPrice.IsZero() { if s.TriggerPrice.IsZero() {
// must call the openGrid method inside the OnStart callback because
// it needs to receive the trades from the user data stream
//
// should try to avoid blocking the user data stream
// callbacks are blocking operation
session.UserDataStream.OnStart(func() { session.UserDataStream.OnStart(func() {
s.logger.Infof("user data stream started, initializing grid...") s.logger.Infof("user data stream started, initializing grid...")
if s.RecoverOrdersWhenStart { if s.RecoverOrdersWhenStart && !bbgo.IsBackTesting {
// avoid blocking the user data stream // do recover only when triggerPrice is not set and not in the back-test mode
// callbacks are blocking operation
// do recover only when triggerPrice is not set.
go func() {
s.logger.Infof("recoverWhenStart is set, trying to recover grid orders...") s.logger.Infof("recoverWhenStart is set, trying to recover grid orders...")
if err := s.recoverGrid(ctx, session); err != nil { if err := s.recoverGrid(ctx, session); err != nil {
log.WithError(err).Errorf("recover error") log.WithError(err).Errorf("recover error")
} }
if err := s.openGrid(ctx, session); err != nil {
s.logger.WithError(err).Errorf("failed to setup grid orders")
} }
}()
} else {
// avoid using goroutine here for back-test // avoid using goroutine here for back-test
if err := s.openGrid(ctx, session); err != nil { if err := s.openGrid(ctx, session); err != nil {
s.logger.WithError(err).Errorf("failed to setup grid orders") s.logger.WithError(err).Errorf("failed to setup grid orders")
} }
}
}) })
} }