mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-27 17:25:16 +00:00
79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package indicator
|
|
|
|
import (
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
)
|
|
|
|
// Refer: Triple Exponential Moving Average (TEMA)
|
|
// URL: https://investopedia.com/terms/t/triple-exponential-moving-average.asp
|
|
|
|
//go:generate callbackgen -type TEMA
|
|
type TEMA struct {
|
|
types.IntervalWindow
|
|
Values types.Float64Slice
|
|
A1 *EWMA
|
|
A2 *EWMA
|
|
A3 *EWMA
|
|
|
|
UpdateCallbacks []func(value float64)
|
|
}
|
|
|
|
func (inc *TEMA) Update(value float64) {
|
|
if len(inc.Values) == 0 {
|
|
inc.A1 = &EWMA{IntervalWindow: types.IntervalWindow{inc.Interval, inc.Window}}
|
|
inc.A2 = &EWMA{IntervalWindow: types.IntervalWindow{inc.Interval, inc.Window}}
|
|
inc.A3 = &EWMA{IntervalWindow: types.IntervalWindow{inc.Interval, inc.Window}}
|
|
}
|
|
inc.A1.Update(value)
|
|
a1 := inc.A1.Last()
|
|
inc.A2.Update(a1)
|
|
a2 := inc.A2.Last()
|
|
inc.A3.Update(a2)
|
|
a3 := inc.A3.Last()
|
|
inc.Values.Push(3*a1 - 3*a2 + a3)
|
|
}
|
|
|
|
func (inc *TEMA) Last() float64 {
|
|
if len(inc.Values) > 0 {
|
|
return inc.Values[len(inc.Values)-1]
|
|
}
|
|
return 0.0
|
|
}
|
|
|
|
func (inc *TEMA) Index(i int) float64 {
|
|
if i >= len(inc.Values) {
|
|
return 0
|
|
}
|
|
return inc.Values[len(inc.Values)-i-1]
|
|
}
|
|
|
|
func (inc *TEMA) Length() int {
|
|
return len(inc.Values)
|
|
}
|
|
|
|
var _ types.Series = &TEMA{}
|
|
|
|
func (inc *TEMA) calculateAndUpdate(allKLines []types.KLine) {
|
|
if inc.A1 == nil {
|
|
for _, k := range allKLines {
|
|
inc.Update(k.Close.Float64())
|
|
inc.EmitUpdate(inc.Last())
|
|
}
|
|
} else {
|
|
inc.Update(allKLines[len(allKLines)-1].Close.Float64())
|
|
inc.EmitUpdate(inc.Last())
|
|
}
|
|
}
|
|
|
|
func (inc *TEMA) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
|
|
if inc.Interval != interval {
|
|
return
|
|
}
|
|
|
|
inc.calculateAndUpdate(window)
|
|
}
|
|
|
|
func (inc *TEMA) Bind(updater KLineWindowUpdater) {
|
|
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
|
|
}
|