From fa395b0d0a4b7bc6a8a5b58aaac6e987ac263f1a Mon Sep 17 00:00:00 2001 From: c9s Date: Fri, 3 Mar 2023 18:22:31 +0800 Subject: [PATCH] grid2: improve the onStart handler --- pkg/strategy/grid2/strategy.go | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/pkg/strategy/grid2/strategy.go b/pkg/strategy/grid2/strategy.go index a56efd3fa..4341fe0e3 100644 --- a/pkg/strategy/grid2/strategy.go +++ b/pkg/strategy/grid2/strategy.go @@ -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 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() { s.logger.Infof("user data stream started, initializing grid...") - if s.RecoverOrdersWhenStart { - // avoid blocking the user data stream - // 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...") - if err := s.recoverGrid(ctx, session); err != nil { - 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 - if err := s.openGrid(ctx, session); err != nil { - s.logger.WithError(err).Errorf("failed to setup grid orders") + if s.RecoverOrdersWhenStart && !bbgo.IsBackTesting { + // do recover only when triggerPrice is not set and not in the back-test mode + s.logger.Infof("recoverWhenStart is set, trying to recover grid orders...") + if err := s.recoverGrid(ctx, session); err != nil { + log.WithError(err).Errorf("recover error") } } + + // avoid using goroutine here for back-test + if err := s.openGrid(ctx, session); err != nil { + s.logger.WithError(err).Errorf("failed to setup grid orders") + } }) }