diff --git a/pkg/bbgo/session.go b/pkg/bbgo/session.go index ab8951a61..0e863eef5 100644 --- a/pkg/bbgo/session.go +++ b/pkg/bbgo/session.go @@ -31,22 +31,24 @@ type StandardIndicatorSet struct { Symbol string // Standard indicators // interval -> window - sma map[types.IntervalWindow]*indicator.SMA - ewma map[types.IntervalWindow]*indicator.EWMA - boll map[types.IntervalWindow]*indicator.BOLL - stoch map[types.IntervalWindow]*indicator.STOCH + sma map[types.IntervalWindow]*indicator.SMA + ewma map[types.IntervalWindow]*indicator.EWMA + boll map[types.IntervalWindow]*indicator.BOLL + stoch map[types.IntervalWindow]*indicator.STOCH + volatility map[types.IntervalWindow]*indicator.VOLATILITY store *MarketDataStore } func NewStandardIndicatorSet(symbol string, store *MarketDataStore) *StandardIndicatorSet { set := &StandardIndicatorSet{ - Symbol: symbol, - sma: make(map[types.IntervalWindow]*indicator.SMA), - ewma: make(map[types.IntervalWindow]*indicator.EWMA), - boll: make(map[types.IntervalWindow]*indicator.BOLL), - stoch: make(map[types.IntervalWindow]*indicator.STOCH), - store: store, + Symbol: symbol, + sma: make(map[types.IntervalWindow]*indicator.SMA), + ewma: make(map[types.IntervalWindow]*indicator.EWMA), + boll: make(map[types.IntervalWindow]*indicator.BOLL), + stoch: make(map[types.IntervalWindow]*indicator.STOCH), + volatility: make(map[types.IntervalWindow]*indicator.VOLATILITY), + store: store, } // let us pre-defined commonly used intervals @@ -132,6 +134,18 @@ func (set *StandardIndicatorSet) STOCH(iw types.IntervalWindow) *indicator.STOCH return inc } +// VOLATILITY returns the volatility(stddev) indicator of the given interval and the window size. +func (set *StandardIndicatorSet) VOLATILITY(iw types.IntervalWindow) *indicator.VOLATILITY { + inc, ok := set.volatility[iw] + if !ok { + inc = &indicator.VOLATILITY{IntervalWindow: iw} + inc.Bind(set.store) + set.volatility[iw] = inc + } + + return inc +} + // ExchangeSession presents the exchange connection Session // It also maintains and collects the data returned from the stream. type ExchangeSession struct { diff --git a/pkg/indicator/volatility.go b/pkg/indicator/volatility.go new file mode 100644 index 000000000..aae62e283 --- /dev/null +++ b/pkg/indicator/volatility.go @@ -0,0 +1,97 @@ +package indicator + +import ( + "fmt" + "math" + "time" + + log "github.com/sirupsen/logrus" + + "github.com/c9s/bbgo/pkg/types" +) + +const MaxNumOfVOL = 5_000 +const MaxNumOfVOLTruncateSize = 100 + +//var zeroTime time.Time + +//go:generate callbackgen -type VOLATILITY +type VOLATILITY struct { + types.IntervalWindow + Values types.Float64Slice + EndTime time.Time + + UpdateCallbacks []func(value float64) +} + +func (inc *VOLATILITY) Last() float64 { + if len(inc.Values) == 0 { + return 0.0 + } + return inc.Values[len(inc.Values)-1] +} + +func (inc *VOLATILITY) calculateAndUpdate(klines []types.KLine) { + if len(klines) < inc.Window { + return + } + + var end = len(klines) - 1 + var lastKLine = klines[end] + + if inc.EndTime != zeroTime && lastKLine.GetEndTime().Before(inc.EndTime) { + return + } + + var recentT = klines[end-(inc.Window-1) : end+1] + + volatility, err := calculateVOLATILITY(recentT, inc.Window, KLineClosePriceMapper) + if err != nil { + log.WithError(err).Error("can not calculate volatility") + return + } + inc.Values.Push(volatility) + + if len(inc.Values) > MaxNumOfVOL { + inc.Values = inc.Values[MaxNumOfVOLTruncateSize-1:] + } + + inc.EndTime = klines[end].GetEndTime().Time() + + inc.EmitUpdate(volatility) +} + +func (inc *VOLATILITY) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) { + if inc.Interval != interval { + return + } + + inc.calculateAndUpdate(window) +} + +func (inc *VOLATILITY) Bind(updater KLineWindowUpdater) { + updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate) +} + +func calculateVOLATILITY(klines []types.KLine, window int, priceF KLinePriceMapper) (float64, error) { + length := len(klines) + if length == 0 || length < window { + return 0.0, fmt.Errorf("insufficient elements for calculating VOL with window = %d", window) + } + + sum := 0.0 + for _, k := range klines { + sum += priceF(k) + } + + avg := sum / float64(window) + sv := 0.0 // sum of variance + + for _, j := range klines { + // The use of Pow math function func Pow(x, y float64) float64 + sv += math.Pow(priceF(j)-avg, 2) + } + // The use of Sqrt math function func Sqrt(x float64) float64 + sd := math.Sqrt(sv / float64(len(klines))) + return sd, nil +} diff --git a/pkg/indicator/volatility_callbacks.go b/pkg/indicator/volatility_callbacks.go new file mode 100644 index 000000000..9f5311d75 --- /dev/null +++ b/pkg/indicator/volatility_callbacks.go @@ -0,0 +1,15 @@ +// Code generated by "callbackgen -type VOLATILITY"; DO NOT EDIT. + +package indicator + +import () + +func (inc *VOLATILITY) OnUpdate(cb func(value float64)) { + inc.UpdateCallbacks = append(inc.UpdateCallbacks, cb) +} + +func (inc *VOLATILITY) EmitUpdate(value float64) { + for _, cb := range inc.UpdateCallbacks { + cb(value) + } +}