|
| 1 | +package core |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/c9s/bbgo/pkg/fixedpoint" |
| 10 | + "github.com/c9s/bbgo/pkg/types" |
| 11 | + "github.com/sirupsen/logrus" |
| 12 | +) |
| 13 | + |
| 14 | +// KLineBuilder is a kline builder for a symbol |
| 15 | +// It will accumulate trades and build klines |
| 16 | +// |
| 17 | +//go:generate callbackgen -type kLineBuilder |
| 18 | +type kLineBuilder struct { |
| 19 | + symbol string |
| 20 | + minInterval types.Interval |
| 21 | + intervals map[types.Interval]struct{} |
| 22 | + isBackTesting bool |
| 23 | + // klinesMap is a map from interval to accumulated kline of that interval |
| 24 | + klinesMap map[types.Interval]*types.KLine |
| 25 | + |
| 26 | + kLineCallbacks []func(kline types.KLine) |
| 27 | + kLineClosedCallbacks []func(kline types.KLine) |
| 28 | + logger *logrus.Entry |
| 29 | + |
| 30 | + // the following fields should be protected by lock when being updated |
| 31 | + mu sync.Mutex |
| 32 | + open, high, low, close, volume, quoteVolume, price fixedpoint.Value |
| 33 | + updateTime types.Time |
| 34 | + numTrades uint64 |
| 35 | +} |
| 36 | + |
| 37 | +// NewKLineBuilder: constructor of kLineBuilder |
| 38 | +// - symbol: symbol to trace on |
| 39 | +// - minInterval: unit interval, related to your signal timeframe. |
| 40 | +// All the supported intervals of the binding stream should be multiple of this interval. |
| 41 | +func NewKLineBuilder(symbol string, minInterval types.Interval, isBackTesting bool) *kLineBuilder { |
| 42 | + logger := logrus.WithField("symbol", symbol) |
| 43 | + return &kLineBuilder{ |
| 44 | + symbol: symbol, |
| 45 | + minInterval: minInterval, |
| 46 | + intervals: make(map[types.Interval]struct{}), |
| 47 | + isBackTesting: isBackTesting, |
| 48 | + klinesMap: make(map[types.Interval]*types.KLine), |
| 49 | + logger: logger, |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func (c *kLineBuilder) Subscribe(interval types.Interval) { |
| 54 | + c.intervals[interval] = struct{}{} |
| 55 | +} |
| 56 | + |
| 57 | +func (c *kLineBuilder) BindStream(stream types.Stream) { |
| 58 | + if c.isBackTesting { |
| 59 | + stream.OnKLineClosed(c.handleKLineClosed) |
| 60 | + stream.OnKLine(c.handleKLine) |
| 61 | + return |
| 62 | + } |
| 63 | + stream.OnMarketTrade(c.handleMarketTrade) |
| 64 | +} |
| 65 | + |
| 66 | +func (c *kLineBuilder) handleKLine(kline types.KLine) { |
| 67 | + c.EmitKLine(kline) |
| 68 | +} |
| 69 | + |
| 70 | +func (c *kLineBuilder) handleKLineClosed(kline types.KLine) { |
| 71 | + c.EmitKLineClosed(kline) |
| 72 | +} |
| 73 | + |
| 74 | +func (c *kLineBuilder) handleMarketTrade(trade types.Trade) { |
| 75 | + // the market data stream may subscribe to trades of multiple symbols |
| 76 | + // so we need to check if the trade is for the symbol we are interested in |
| 77 | + if trade.Symbol != c.symbol { |
| 78 | + return |
| 79 | + } |
| 80 | + c.mu.Lock() |
| 81 | + defer c.mu.Unlock() |
| 82 | + |
| 83 | + c.price = trade.Price |
| 84 | + c.close = trade.Price |
| 85 | + if !c.high.IsZero() { |
| 86 | + if c.price.Compare(c.high) > 0 { |
| 87 | + c.high = c.price |
| 88 | + } |
| 89 | + } else { |
| 90 | + c.high = c.price |
| 91 | + } |
| 92 | + if !c.low.IsZero() { |
| 93 | + if c.price.Compare(c.low) < 0 { |
| 94 | + c.low = c.price |
| 95 | + } |
| 96 | + } else { |
| 97 | + c.low = c.price |
| 98 | + } |
| 99 | + if c.open.IsZero() { |
| 100 | + c.open = c.price |
| 101 | + } |
| 102 | + c.volume = c.volume.Add(trade.Quantity) |
| 103 | + c.quoteVolume = c.quoteVolume.Add(trade.QuoteQuantity) |
| 104 | + c.numTrades++ |
| 105 | + c.updateTime = trade.Time |
| 106 | +} |
| 107 | + |
| 108 | +func (c *kLineBuilder) Run(ctx context.Context) { |
| 109 | + if len(c.intervals) == 0 || c.isBackTesting { |
| 110 | + return |
| 111 | + } |
| 112 | + minDuration := c.minInterval.Duration() |
| 113 | + for interval := range c.intervals { |
| 114 | + if interval.Duration()%minDuration != 0 { |
| 115 | + err := fmt.Errorf("interval %s is not a multiple of minInterval %s", interval, c.minInterval) |
| 116 | + c.logger.Error(err) |
| 117 | + panic(err) |
| 118 | + } |
| 119 | + } |
| 120 | + c.logger.Infof("kline updater started for %s (%+v)", c.symbol, c.intervals) |
| 121 | + go c.update(ctx) |
| 122 | +} |
| 123 | + |
| 124 | +func (c *kLineBuilder) update(ctx context.Context) { |
| 125 | + // wait for the next interval |
| 126 | + startTime := time.Now() |
| 127 | + c.updateTime = types.Time(startTime) // kick-start update time |
| 128 | + startTimeRound := startTime.Round(c.minInterval.Duration()) |
| 129 | + waitDuration := startTimeRound.Sub(startTime) |
| 130 | + if waitDuration > 0 { |
| 131 | + select { |
| 132 | + case <-time.After(waitDuration): |
| 133 | + case <-ctx.Done(): |
| 134 | + return |
| 135 | + } |
| 136 | + } |
| 137 | + // start ticker |
| 138 | + intervalDuration := c.minInterval.Duration() |
| 139 | + ticker := time.NewTicker(intervalDuration) |
| 140 | + defer ticker.Stop() |
| 141 | + |
| 142 | + for { |
| 143 | + select { |
| 144 | + case <-ctx.Done(): |
| 145 | + return |
| 146 | + case tickTime := <-ticker.C: |
| 147 | + startTime := tickTime.Add(-1 * intervalDuration).Round(intervalDuration) |
| 148 | + |
| 149 | + // construct kline and reset converter |
| 150 | + c.mu.Lock() |
| 151 | + lastTradeTime := c.updateTime |
| 152 | + klineMinInterval := types.KLine{ |
| 153 | + Symbol: c.symbol, |
| 154 | + StartTime: types.Time(startTime), |
| 155 | + EndTime: types.Time(tickTime), |
| 156 | + Interval: c.minInterval, |
| 157 | + Closed: true, |
| 158 | + } |
| 159 | + klineMinInterval.Open = c.open |
| 160 | + klineMinInterval.Close = c.close |
| 161 | + klineMinInterval.High = c.high |
| 162 | + klineMinInterval.Low = c.low |
| 163 | + klineMinInterval.Volume = c.volume |
| 164 | + klineMinInterval.QuoteVolume = c.quoteVolume |
| 165 | + klineMinInterval.NumberOfTrades = c.numTrades |
| 166 | + c.open = fixedpoint.Zero |
| 167 | + c.close = fixedpoint.Zero |
| 168 | + c.high = fixedpoint.Zero |
| 169 | + c.low = fixedpoint.Zero |
| 170 | + c.volume = fixedpoint.Zero |
| 171 | + c.quoteVolume = fixedpoint.Zero |
| 172 | + c.numTrades = 0 |
| 173 | + c.mu.Unlock() |
| 174 | + |
| 175 | + // update klines map |
| 176 | + c.updateKLinesMap(&klineMinInterval, lastTradeTime) |
| 177 | + } |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +func (c *kLineBuilder) updateKLinesMap(klineMinInterval *types.KLine, lastUpdateTime types.Time) { |
| 182 | + for interval := range c.intervals { |
| 183 | + if interval == c.minInterval { |
| 184 | + c.EmitKLineClosed(*klineMinInterval) |
| 185 | + continue |
| 186 | + } |
| 187 | + kline, ok := c.klinesMap[interval] |
| 188 | + if !ok { |
| 189 | + // interval not in map and kline is nil |
| 190 | + kline = &types.KLine{} |
| 191 | + kline.Set(klineMinInterval) |
| 192 | + c.klinesMap[interval] = kline |
| 193 | + } else { |
| 194 | + kline.Merge(klineMinInterval) |
| 195 | + } |
| 196 | + kline.Interval = interval |
| 197 | + expectEndTime := kline.StartTime.Time().Add(interval.Duration()) |
| 198 | + kline.Closed = expectEndTime.Before(klineMinInterval.EndTime.Time()) || lastUpdateTime.After(expectEndTime) |
| 199 | + |
| 200 | + if kline.Closed { |
| 201 | + c.EmitKLineClosed(*kline) |
| 202 | + delete(c.klinesMap, interval) |
| 203 | + } else { |
| 204 | + c.EmitKLine(*kline) |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments