bbgo: move struct field inherits to the dynamic package

This commit is contained in:
c9s 2022-07-06 13:37:52 +08:00
parent 3d9db2786d
commit 8236004b4f
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 24 additions and 17 deletions

View File

@ -1,8 +1,6 @@
package bbgo
import (
"reflect"
"github.com/pkg/errors"
"github.com/c9s/bbgo/pkg/dynamic"
@ -32,21 +30,7 @@ type ExitMethod struct {
// Inherit is used for inheriting properties from the given strategy struct
// for example, some exit method requires the default interval and symbol name from the strategy param object
func (m *ExitMethod) Inherit(parent interface{}) {
// we need to pass some information from the strategy configuration to the exit methods, like symbol, interval and window
rt := reflect.TypeOf(m).Elem()
rv := reflect.ValueOf(m).Elem()
for j := 0; j < rv.NumField(); j++ {
if !rt.Field(j).IsExported() {
continue
}
fieldValue := rv.Field(j)
if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
continue
}
dynamic.InheritStructValues(fieldValue.Interface(), parent)
}
dynamic.StructFieldsInherit(m, parent)
}
func (m *ExitMethod) Subscribe(session *ExchangeSession) {

View File

@ -2,6 +2,29 @@ package dynamic
import "reflect"
// StructFieldsInherit is used for inheriting properties from the given strategy struct
// for example, some exit method requires the default interval and symbol name from the strategy param object
func StructFieldsInherit(m interface{}, parent interface{}) {
// we need to pass some information from the strategy configuration to the exit methods, like symbol, interval and window
rt := reflect.TypeOf(m).Elem()
rv := reflect.ValueOf(m).Elem()
for j := 0; j < rv.NumField(); j++ {
if !rt.Field(j).IsExported() {
continue
}
fieldValue := rv.Field(j)
if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
continue
}
InheritStructValues(fieldValue.Interface(), parent)
}
}
// InheritStructValues merges the field value from the source struct to the dest struct.
// Only fields with the same type and the same name will be updated.
func InheritStructValues(dst, src interface{}) {