package indicator import ( "sig-pub/pkg/types" ) // Macd macd柱状图计算 // Macd 拆分成: Macd(柱状图), MacdDIF线, MacdDEA(信号线) // 计算 MacdDIF 线 (DIF): 反映短期趋势与长期趋势的“收敛/散度” // Macd: https://www.investopedia.com/terms/m/macd.asp type Macd struct { } func (c *Macd) Meta() IndicatorMeta { return IndicatorMeta{ Name: "macd", Input: []types.InputArg{ {Name: "fast", Type: types.InputTypeUInt, Desc: "快线周期"}, {Name: "slow", Type: types.InputTypeUInt, Desc: "慢线周期"}, {Name: "singal", Type: types.InputTypeUInt, Desc: "信号线周期"}, }, } } func (c *Macd) CandlePeriods(ctx IIndicatorContext) int16 { return max( ctx.Indicator("macd_dif", ctx.Input()).CandlePeriods(), ctx.Indicator("macd_dea", ctx.Input()).CandlePeriods(), ) } func (c *Macd) Calculate(ctx IIndicatorContext) (vector float64) { macd_dea := ctx.Indicator("macd_dea", ctx.Input()).Get(0) macd_dif := ctx.Indicator("macd_dif", ctx.Input()).Get(0) vector = (macd_dif - macd_dea) * 2 return } type MacdDIF struct { } // indicator interface func (c *MacdDIF) Meta() IndicatorMeta { return IndicatorMeta{ Name: "macd_dif", Input: []types.InputArg{ {Name: "fast", Type: types.InputTypeUInt, Desc: "快线周期"}, {Name: "slow", Type: types.InputTypeUInt, Desc: "慢线周期"}, }, } } func (c *MacdDIF) CandlePeriods(ctx IIndicatorContext) int16 { return max( ctx.Indicator("ema", ctx.Input().Int16("fast")).CandlePeriods(), ctx.Indicator("ema", ctx.Input().Int16("slow")).CandlePeriods(), ) } // Calculate 计算单根k线sma指标 func (c *MacdDIF) Calculate(ctx IIndicatorContext) (vector float64) { fast := ctx.Input().Int16("fast") // 12 slow := ctx.Input().Int16("slow") // 26 // macd计算从第max(fast, slow)期开始稳定 fastEma := ctx.Indicator("ema", fast).Get(0) slowEma := ctx.Indicator("ema", slow).Get(0) macd := fastEma - slowEma vector = macd return } // MacdDEA macd信号线计算 type MacdDEA struct { } func (c *MacdDEA) Meta() IndicatorMeta { return IndicatorMeta{ Name: "macd_dea", Input: []types.InputArg{ {Name: "fast", Type: types.InputTypeUInt, Desc: "快线周期"}, {Name: "slow", Type: types.InputTypeUInt, Desc: "慢线周期"}, {Name: "singal", Type: types.InputTypeUInt, Desc: "信号线周期"}, }, } } func (c *MacdDEA) CandlePeriods(ctx IIndicatorContext) int16 { return ctx.Indicator("macd_dif", ctx.Input()).CandlePeriods() + ctx.Input().Int16("singal") + 1 } func (c *MacdDEA) Calculate(ctx IIndicatorContext) (vector float64) { singal := ctx.Input().Int16("singal") // 9 deaPrev, ok := ctx.State().Get("vector", 1) if !ok { // 初始值前9期的 MACD_DIF SMA macdDifs := ctx.Indicator("macd_dif", ctx.Input()).Series(1, singal) deaPrev = macdDifs.Avg() } macd_dif := ctx.Indicator("macd_dif", ctx.Input()).Get(0) // 计算DEA beta := 2 / float64(singal+1) dea := beta*macd_dif + (1-beta)*deaPrev ctx.State().Set("vector", dea) vector = dea return }