From 263c0883d10e82a6ea95fc64e129eeecc3f015f5 Mon Sep 17 00:00:00 2001 From: c9s Date: Wed, 29 Nov 2023 16:35:37 +0800 Subject: [PATCH] bbgo: solve the scale when unmarshalling the json --- pkg/bbgo/scale.go | 13 +++++++++++++ pkg/bbgo/scale_test.go | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/pkg/bbgo/scale.go b/pkg/bbgo/scale.go index 207a42589..b973319b6 100644 --- a/pkg/bbgo/scale.go +++ b/pkg/bbgo/scale.go @@ -1,6 +1,7 @@ package bbgo import ( + "encoding/json" "fmt" "math" @@ -318,6 +319,18 @@ type LayerScale struct { LayerRule *SlideRule `json:"byLayer"` } +func (s *LayerScale) UnmarshalJSON(data []byte) error { + type T LayerScale + var p T + err := json.Unmarshal(data, &p) + if err != nil { + return err + } + + *s = LayerScale(p) + return nil +} + func (s *LayerScale) Scale(layer int) (quantity float64, err error) { if s.LayerRule == nil { err = errors.New("either price or volume scale is not defined") diff --git a/pkg/bbgo/scale_test.go b/pkg/bbgo/scale_test.go index 1ad86a0c4..a193747cd 100644 --- a/pkg/bbgo/scale_test.go +++ b/pkg/bbgo/scale_test.go @@ -1,6 +1,7 @@ package bbgo import ( + "encoding/json" "testing" "github.com/stretchr/testify/assert" @@ -8,6 +9,24 @@ import ( const delta = 1e-9 +func TestLayerScale_UnmarshalJSON(t *testing.T) { + var s LayerScale + err := json.Unmarshal([]byte(`{ + "byLayer": { + "linear": { + "domain": [ 1, 3 ], + "range": [ 10000.0, 30000.0 ] + } + } + }`), &s) + assert.NoError(t, err) + + if assert.NotNil(t, s.LayerRule) { + assert.NotNil(t, s.LayerRule.LinearScale.Range) + assert.NotNil(t, s.LayerRule.LinearScale.Domain) + } +} + func TestExponentialScale(t *testing.T) { // graph see: https://www.desmos.com/calculator/ip0ijbcbbf scale := ExponentialScale{