From 3e6d6e10b3f5326cff3e6c32468a417f19cf0d7c Mon Sep 17 00:00:00 2001 From: c9s Date: Mon, 18 Dec 2023 12:09:03 +0800 Subject: [PATCH] all: move Initialize() call out, call it before the LoadState --- cmd/bbgo-webview/main.go | 5 +++++ pkg/bbgo/trader.go | 21 ++++++++++++--------- pkg/cmd/run.go | 4 ++++ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/cmd/bbgo-webview/main.go b/cmd/bbgo-webview/main.go index 7cc5060e2..e863c2c61 100644 --- a/cmd/bbgo-webview/main.go +++ b/cmd/bbgo-webview/main.go @@ -109,6 +109,11 @@ func main() { return } + if err := trader.Initialize(ctx); err != nil { + log.WithError(err).Error("failed to initialize strategies") + return + } + if err := trader.LoadState(ctx); err != nil { log.WithError(err).Error("failed to load strategy states") return diff --git a/pkg/bbgo/trader.go b/pkg/bbgo/trader.go index 6c21f1a4d..44be5c2a0 100644 --- a/pkg/bbgo/trader.go +++ b/pkg/bbgo/trader.go @@ -16,8 +16,8 @@ import ( ) // Strategy method calls: -// -> Defaults() (optional method) // -> Initialize() (optional method) +// -> Defaults() (optional method) // -> Validate() (optional method) // -> Run() (optional method) // -> Shutdown(shutdownCtx context.Context, wg *sync.WaitGroup) @@ -244,12 +244,6 @@ func (trader *Trader) injectFieldsAndSubscribe(ctx context.Context) error { } } - if initializer, ok := strategy.(StrategyInitializer); ok { - if err := initializer.Initialize(); err != nil { - panic(err) - } - } - if subscriber, ok := strategy.(ExchangeSessionSubscriber); ok { subscriber.Subscribe(session) } else { @@ -362,17 +356,26 @@ func (trader *Trader) Run(ctx context.Context) error { return trader.environment.Connect(ctx) } +func (trader *Trader) Initialize(ctx context.Context) error { + log.Infof("initializing strategies...") + return trader.IterateStrategies(func(strategy StrategyID) error { + if initializer, ok := strategy.(StrategyInitializer); ok { + return initializer.Initialize() + } + + return nil + }) +} + func (trader *Trader) LoadState(ctx context.Context) error { if trader.environment.BacktestService != nil { return nil } isolation := GetIsolationFromContext(ctx) - ps := isolation.persistenceServiceFacade.Get() log.Infof("loading strategies states...") - return trader.IterateStrategies(func(strategy StrategyID) error { id := dynamic.CallID(strategy) return loadPersistenceFields(strategy, id, ps) diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index bc601e0dc..92e1bbe8a 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -163,6 +163,10 @@ func runConfig(basectx context.Context, cmd *cobra.Command, userConfig *bbgo.Con return err } + if err := trader.Initialize(tradingCtx); err != nil { + return err + } + if err := trader.LoadState(tradingCtx); err != nil { return err }