bbgo: solve the scale when unmarshalling the json

This commit is contained in:
c9s 2023-11-29 16:35:37 +08:00
parent d123e89a1b
commit 263c0883d1
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 32 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package bbgo package bbgo
import ( import (
"encoding/json"
"fmt" "fmt"
"math" "math"
@ -318,6 +319,18 @@ type LayerScale struct {
LayerRule *SlideRule `json:"byLayer"` 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) { func (s *LayerScale) Scale(layer int) (quantity float64, err error) {
if s.LayerRule == nil { if s.LayerRule == nil {
err = errors.New("either price or volume scale is not defined") err = errors.New("either price or volume scale is not defined")

View File

@ -1,6 +1,7 @@
package bbgo package bbgo
import ( import (
"encoding/json"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -8,6 +9,24 @@ import (
const delta = 1e-9 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) { func TestExponentialScale(t *testing.T) {
// graph see: https://www.desmos.com/calculator/ip0ijbcbbf // graph see: https://www.desmos.com/calculator/ip0ijbcbbf
scale := ExponentialScale{ scale := ExponentialScale{