bbgo_origin/pkg/fixedpoint/convert.go

144 lines
2.3 KiB
Go
Raw Normal View History

2020-10-02 12:50:05 +00:00
package fixedpoint
import (
"encoding/json"
2020-11-09 08:34:35 +00:00
"fmt"
2020-10-02 12:50:05 +00:00
"math"
"strconv"
"sync/atomic"
2020-10-02 12:50:05 +00:00
)
const DefaultPrecision = 8
const DefaultPow = 1e8
type Value int64
func (v Value) Float64() float64 {
return float64(v) / DefaultPow
}
2020-10-03 03:11:59 +00:00
func (v Value) Int64() int64 {
return int64(v)
}
2020-10-02 12:50:05 +00:00
func (v Value) Mul(v2 Value) Value {
return NewFromFloat(v.Float64() * v2.Float64())
}
2020-10-03 05:44:38 +00:00
func (v Value) MulFloat64(v2 float64) Value {
return NewFromFloat(v.Float64() * v2)
}
2020-10-02 12:50:05 +00:00
func (v Value) Div(v2 Value) Value {
return NewFromFloat(v.Float64() / v2.Float64())
}
func (v Value) Sub(v2 Value) Value {
return Value(int64(v) - int64(v2))
}
func (v Value) Add(v2 Value) Value {
return Value(int64(v) + int64(v2))
}
func (v *Value) AtomicAdd(v2 Value) {
atomic.AddInt64((*int64)(v), int64(v2))
}
func (v *Value) AtomicLoad() Value {
i := atomic.LoadInt64((*int64)(v))
return Value(i)
}
2020-10-26 09:57:28 +00:00
func (v *Value) UnmarshalYAML(unmarshal func(a interface{}) error) (err error) {
var f float64
if err = unmarshal(&f); err == nil {
*v = NewFromFloat(f)
return
}
2020-11-10 06:19:22 +00:00
var i int64
if err = unmarshal(&i); err == nil {
*v = NewFromInt64(i)
return
}
2020-10-26 09:57:28 +00:00
var s string
if err = unmarshal(&s); err == nil {
nv, err2 := NewFromString(s)
if err2 == nil {
*v = nv
return
}
}
return err
}
2020-12-07 15:03:06 +00:00
func (v Value) MarshalJSON() ([]byte, error) {
f := float64(v) / DefaultPow
2021-01-25 07:32:17 +00:00
o := strconv.FormatFloat(f, 'f', 8, 64)
2020-12-07 15:03:06 +00:00
return []byte(o), nil
}
func (v *Value) UnmarshalJSON(data []byte) error {
var a interface{}
var err = json.Unmarshal(data, &a)
if err != nil {
return err
}
switch d := a.(type) {
case float64:
*v = NewFromFloat(d)
case float32:
*v = NewFromFloat32(d)
case int:
*v = NewFromInt(d)
case int64:
*v = NewFromInt64(d)
default:
2020-11-09 08:34:35 +00:00
return fmt.Errorf("unsupported type: %T %v", d, d)
}
return nil
}
2020-11-10 06:19:22 +00:00
func Must(v Value, err error) Value {
if err != nil {
panic(err)
}
return v
}
2020-10-02 12:50:05 +00:00
func NewFromString(input string) (Value, error) {
v, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, err
}
return NewFromFloat(v), nil
}
func NewFromFloat(val float64) Value {
return Value(int64(math.Round(val * DefaultPow)))
}
2020-10-03 03:11:59 +00:00
func NewFromFloat32(val float32) Value {
return Value(int64(math.Round(float64(val) * DefaultPow)))
}
2020-10-03 03:11:59 +00:00
func NewFromInt(val int) Value {
return Value(int64(val * DefaultPow))
}
func NewFromInt64(val int64) Value {
return Value(val * DefaultPow)
}