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