blockchain/internal/lib/strategy/ema.go

28 lines
659 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package strategy
import "github.com/shopspring/decimal"
/************** EMA 指數移動平均 **************/
type EMA struct {
n int
alp decimal.Decimal // 平滑係數 α = 2 / (n + 1)
val decimal.Decimal // 當前EMA值
ok bool
}
func NewEMA(n int) *EMA {
return &EMA{n: n, alp: decimal.NewFromFloat(2.0).Div(decimal.NewFromInt(int64(n + 1)))}
}
func (e *EMA) Push(close decimal.Decimal) (decimal.Decimal, bool) {
if !e.ok {
// 第一筆資料直接當作EMA初始值
e.val = close
e.ok = true
return e.val, false
}
// EMA計算公式
e.val = e.alp.Mul(close).Add(decimal.NewFromInt(1).Sub(e.alp).Mul(e.val))
return e.val, true
}