Skip to content

Instantly share code, notes, and snippets.

@ivank2139
Created April 5, 2020 03:42
Show Gist options
  • Save ivank2139/53cb678f8c5e7aa57bf0c51bc7e29085 to your computer and use it in GitHub Desktop.
Save ivank2139/53cb678f8c5e7aa57bf0c51bc7e29085 to your computer and use it in GitHub Desktop.
An implementation of MACD in Go.
package indicator
import (
"strings"
"github.com/shopspring/decimal"
)
/*
This indicator consists of 3 main parts:
The standard MACD is calculated using the closing prices of a 12-day exponential moving average (EMA) minus a 26-day EMA.
The signal is a 9-day EMA next to the MACD line and it signals turns in the indicator.
The third part is called the MACD-Histogram which shows the difference between the MACD line and the signal line and is
plotted either above or below a zero line.
*/
type Macd struct {
Histogram decimal.Decimal
Diff decimal.Decimal
Result decimal.Decimal
Ema12 *Ema
Ema26 *Ema
Ema9 *Ema
Hup bool
Hdn bool
}
func NewMacd() *Macd {
macd := Macd{}
macd.Ema12 = NewEma(decimal.NewFromInt(MacdShort))
macd.Ema26 = NewEma(decimal.NewFromInt(MacdLong))
macd.Ema9 = NewEma(decimal.NewFromInt(MacdSignal))
return &macd
}
func (m *Macd) Update(f decimal.Decimal) {
pmacd := *m
m.Diff = m.Ema12.Update(f).Sub(m.Ema26.Update(f))
m.Result = m.Ema9.Update(m.Diff)
m.Histogram = m.Result.Sub(m.Diff)
m.Hup = pmacd.Histogram.LessThanOrEqual(decimal.Zero) && m.Histogram.GreaterThan(decimal.Zero)
m.Hdn = pmacd.Histogram.GreaterThan(decimal.Zero) && m.Histogram.LessThanOrEqual(decimal.Zero)
}
func (m *Macd) String() string {
var bldr = strings.Builder{}
bldr.WriteString("Macd values:")
bldr.WriteString("Histogram " + m.Histogram.String())
bldr.WriteString("Diff " + m.Diff.String())
bldr.WriteString("Result " + m.Result.String())
bldr.WriteString("Ema12 Result " + m.Ema12.Result.String())
bldr.WriteString("Ema26 Result " + m.Ema26.Result.String())
bldr.WriteString("Ema9 Result " + m.Ema9.Result.String())
return bldr.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment