All files / core candleManager.js

100% Statements 68/68
88.23% Branches 30/34
100% Functions 15/15
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238                              2x                                     39x 39x 39x     39x             39x 44x 1x 1x   43x         39x 39x 43x                                       89x 89x   89x 89x 89x     89x 89x   89x   30x             59x   19x 19x     19x     19x                 40x     89x     89x                   13x 13x 1x 1x     12x 12x                 20x 20x 19x               2x 2x 4x   2x             3x 3x 3x                   49x                                   40x 40x 40x 40x 40x 40x             19x 19x 19x 19x     19x     19x 1x     19x 19x             274x       2x  
/**
 * candleManager.js
 *
 * Manages OHLCV candlestick data per symbol.
 *
 * Features:
 * - Multiple configurable intervals (1s, 1m, 5m, 15m, 1h, 4h, 1d)
 * - Accurate OHLCV — open is always first tick of interval
 * - Emits completed candle when interval closes
 * - Keeps rolling history (configurable max candles)
 * - No double-append bug from old code
 */
 
"use strict";
 
const INTERVALS = {
  "1s": 1000,
  "1m": 60 * 1000,
  "5m": 5 * 60 * 1000,
  "15m": 15 * 60 * 1000,
  "1h": 60 * 60 * 1000,
  "4h": 4 * 60 * 60 * 1000,
  "1d": 24 * 60 * 60 * 1000,
};
 
class CandleManager {
  /**
   * @param {Object} config
   * @param {string|string[]} config.intervals  - e.g. '1m' or ['1m','5m','1h']
   * @param {number} config.precision           - Decimal places for price
   * @param {number} config.maxCandles          - Max candles to keep per interval (default 1000)
   * @param {Function} config.onClose           - Callback when candle closes: (candle) => {}
   */
  constructor(config = {}) {
    this.precision = config.precision ?? 2;
    this.maxCandles = config.maxCandles ?? 1000;
    this.onClose = config.onClose ?? null;
 
    // Normalize intervals to array
    const requested = config.intervals
      ? Array.isArray(config.intervals)
        ? config.intervals
        : [config.intervals]
      : ["1m"];
 
    // Validate intervals
    this.intervals = requested.filter((i) => {
      if (!INTERVALS[i]) {
        console.warn(`[CandleManager] Unknown interval "${i}" — skipped.`);
        return false;
      }
      return true;
    });
 
    // Per-interval state
    // { '1m': { current: Candle|null, history: Candle[] }, ... }
    this._state = {};
    this.intervals.forEach((interval) => {
      this._state[interval] = {
        current: null,
        history: [],
        intervalMs: INTERVALS[interval],
      };
    });
  }
 
  /**
   * Feed a new price tick into the candle manager
   * Call this on every price update
   *
   * @param {number} price     - Current price
   * @param {number} volume    - Volume for this tick
   * @param {number} timestamp - Unix ms timestamp (default: Date.now())
   * @returns {Object} { updated: Object, closed: Object[] }
   *   updated → current in-progress candles per interval
   *   closed  → candles that just completed this tick
   */
  tick(price, volume, timestamp = Date.now()) {
    const updated = {};
    const closed = [];
 
    this.intervals.forEach((interval) => {
      const state = this._state[interval];
      const intervalMs = state.intervalMs;
 
      // Calculate which interval bucket this timestamp belongs to
      const bucketStart = Math.floor(timestamp / intervalMs) * intervalMs;
      const bucketEnd = bucketStart + intervalMs;
 
      if (!state.current) {
        // No open candle — open a new one
        state.current = this._openCandle(
          interval,
          price,
          volume,
          bucketStart,
          bucketEnd,
        );
      } else if (timestamp >= state.current.closeTime) {
        // Current candle has expired — close it and open new one
        const closed_candle = this._closeCandle(state, interval);
        closed.push(closed_candle);
 
        // Fire callback if provided
        if (this.onClose) this.onClose(closed_candle);
 
        // Open new candle
        state.current = this._openCandle(
          interval,
          price,
          volume,
          bucketStart,
          bucketEnd,
        );
      } else {
        // Update existing candle
        this._updateCandle(state.current, price, volume);
      }
 
      updated[interval] = { ...state.current };
    });
 
    return { updated, closed };
  }
 
  /**
   * Get completed candle history for an interval
   * @param {string} interval - e.g. '1m'
   * @param {number} limit    - Max candles to return (default: all)
   * @returns {Array} candles oldest → newest
   */
  getHistory(interval, limit) {
    const state = this._state[interval];
    if (!state) {
      console.warn(`[CandleManager] Unknown interval "${interval}"`);
      return [];
    }
 
    const history = state.history;
    return limit ? history.slice(-limit) : [...history];
  }
 
  /**
   * Get current in-progress candle for an interval
   * @param {string} interval
   * @returns {Object|null}
   */
  getCurrent(interval) {
    const state = this._state[interval];
    if (!state) return null;
    return state.current ? { ...state.current } : null;
  }
 
  /**
   * Get all history for all intervals
   * @returns {Object} { '1m': [...], '5m': [...] }
   */
  getAllHistory() {
    const result = {};
    this.intervals.forEach((interval) => {
      result[interval] = this.getHistory(interval);
    });
    return result;
  }
 
  /**
   * Reset all candle state — call at start of new trading day
   */
  reset() {
    this.intervals.forEach((interval) => {
      this._state[interval].current = null;
      this._state[interval].history = [];
    });
  }
 
  // ── Private helpers ──────────────────────── //
 
  /**
   * Open a new candle
   */
  _openCandle(interval, price, volume, openTime, closeTime) {
    return {
      interval,
      openTime,
      closeTime,
      open: this._round(price),
      high: this._round(price),
      low: this._round(price),
      close: this._round(price),
      volume: volume,
      ticks: 1, // number of price updates in this candle
      closed: false,
    };
  }
 
  /**
   * Update an open candle with new price and volume
   */
  _updateCandle(candle, price, volume) {
    const rounded = this._round(price);
    if (rounded > candle.high) candle.high = rounded;
    if (rounded < candle.low) candle.low = rounded;
    candle.close = rounded;
    candle.volume += volume; // numeric addition — no string bug
    candle.ticks += 1;
  }
 
  /**
   * Close current candle and add to history
   */
  _closeCandle(state, interval) {
    const candle = state.current;
    candle.closed = true;
    candle.close = this._round(candle.close);
    candle.volume = this._round(candle.volume);
 
    // Add to history
    state.history.push(candle);
 
    // Trim history if over max
    if (state.history.length > this.maxCandles) {
      state.history.shift();
    }
 
    state.current = null;
    return candle;
  }
 
  /**
   * Round to configured precision
   */
  _round(value) {
    return parseFloat(value.toFixed(this.precision));
  }
}
 
module.exports = { CandleManager, INTERVALS };