Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEATURE: [indicator] Add VWAP indicator #1258

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkg/bbgo/indicator_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ func (i *IndicatorSet) VOLUME(interval types.Interval) *indicatorv2.PriceStream
return indicatorv2.Volumes(i.KLines(interval))
}

func (i *IndicatorSet) VWAP(iw types.IntervalWindow) *indicatorv2.VWAPStream {
return indicatorv2.VWAP(i.CLOSE(iw.Interval), i.VOLUME(iw.Interval), iw.Window)
}

func (i *IndicatorSet) RSI(iw types.IntervalWindow) *indicatorv2.RSIStream {
return indicatorv2.RSI2(i.CLOSE(iw.Interval), iw.Window)
}
Expand Down
43 changes: 43 additions & 0 deletions pkg/indicator/v2/vwap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package indicatorv2

import (
"github.com/c9s/bbgo/pkg/types"
)

const MaxNumOfVWAP = 500_000

type VWAPStream struct {
*types.Float64Series
window int
rawCloseValues *types.Queue
rawVolumeValues *types.Queue
}

func VWAP(price types.Float64Source, volume types.Float64Source, window int) *VWAPStream {
s := &VWAPStream{
Float64Series: types.NewFloat64Series(),
window: window,
rawCloseValues: types.NewQueue(window),
rawVolumeValues: types.NewQueue(window),
}
price.OnUpdate(func(p float64) {
s.rawCloseValues.Update(p)
s.calculate()
})
volume.OnUpdate(func(v float64) {
s.rawVolumeValues.Update(v)
s.calculate()
})
return s
}

func (s *VWAPStream) calculate() float64 {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to check both the rawCloseValues, rawVolumeValues length, because it could trigger twice since you have 2 update callbacks, or you can subscribe the KLine stream

vwap := s.rawCloseValues.Dot(s.rawVolumeValues) / s.rawVolumeValues.Sum(s.window)
s.Slice.Push(vwap)
s.EmitUpdate(vwap)
return vwap
}

func (s *VWAPStream) Truncate() {
s.Slice = s.Slice.Truncate(MaxNumOfVWAP)
}