All files / core orderBook.js

100% Statements 49/49
68.42% Branches 13/19
100% Functions 9/9
100% Lines 48/48

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                                                    29x 29x 29x 29x 29x       29x 29x                 125x     125x 125x   125x 125x   125x 125x   125x                     74x 1x     73x 73x 73x       73x 73x   73x 73x   73x             6x                             250x 250x   250x   2490x           2490x   2490x               250x                   146x   146x 1460x         1460x 1460x 1460x 1460x   1460x                             2490x       2490x 2490x 2490x   2490x             4544x       1x  
/**
 * orderBook.js
 *
 * Generates realistic bid/ask order book depth
 * around the current market price.
 *
 * Features:
 * - Configurable depth levels
 * - Realistic volume distribution (more volume near mid price)
 * - Price levels use correct tick size
 * - Best bid always < best ask (no crossed book)
 * - Randomized but stable between ticks
 */
 
"use strict";
 
class OrderBook {
  /**
   * @param {Object} config
   * @param {number} config.depth      - Number of levels each side (default: 10)
   * @param {number} config.tickSize   - Minimum price increment (e.g. 0.01)
   * @param {number} config.precision  - Decimal places for price
   * @param {Object} config.volume     - { min, max } volume per level
   * @param {number} config.spreadPct  - Spread as % of price (default: 0.001 = 0.1%)
   */
  constructor(config = {}) {
    this.depth = config.depth ?? 10;
    this.tickSize = config.tickSize ?? 0.01;
    this.precision = config.precision ?? 2;
    this.volume = config.volume ?? { min: 100, max: 5000 };
    this.spreadPct = config.spreadPct ?? 0.001;
 
    // Internal state — small random shifts each tick
    // makes the book feel alive without full regeneration
    this._lastBids = [];
    this._lastAsks = [];
  }
 
  /**
   * Generate full order book snapshot around current price
   * @param {number} price - Current mid price
   * @returns {{ bids: Array, asks: Array }}
   */
  generate(price) {
    const halfSpread = this._round(price * this.spreadPct * 0.5);
 
    // Best bid is below mid, best ask is above mid
    const bestBid = this._round(price - halfSpread);
    const bestAsk = this._round(price + halfSpread);
 
    const bids = this._generateSide("bid", bestBid);
    const asks = this._generateSide("ask", bestAsk);
 
    this._lastBids = bids;
    this._lastAsks = asks;
 
    return { bids, asks };
  }
 
  /**
   * Update existing book with small random changes
   * More efficient than full regeneration every tick
   * @param {number} price - Current mid price
   * @returns {{ bids: Array, asks: Array }}
   */
  update(price) {
    // Full regenerate if no existing book
    if (!this._lastBids.length || !this._lastAsks.length) {
      return this.generate(price);
    }
 
    const halfSpread = this._round(price * this.spreadPct * 0.5);
    const bestBid = this._round(price - halfSpread);
    const bestAsk = this._round(price + halfSpread);
 
    // Regenerate prices from new best bid/ask
    // but randomize volumes slightly for realism
    const bids = this._updateSide("bid", bestBid, this._lastBids);
    const asks = this._updateSide("ask", bestAsk, this._lastAsks);
 
    this._lastBids = bids;
    this._lastAsks = asks;
 
    return { bids, asks };
  }
 
  /**
   * Get current book without updating
   */
  getSnapshot() {
    return {
      bids: this._lastBids,
      asks: this._lastAsks,
    };
  }
 
  // ── Private helpers ──────────────────────── //
 
  /**
   * Generate one side of the order book
   * @param {'bid'|'ask'} side
   * @param {number} bestPrice - Best price on this side
   * @returns {Array} levels sorted best to worst
   */
  _generateSide(side, bestPrice) {
    const levels = [];
    const isBid = side === "bid";
 
    for (let i = 0; i < this.depth; i++) {
      // Price moves away from mid for each level
      const levelPrice = isBid
        ? this._round(bestPrice - i * this.tickSize)
        : this._round(bestPrice + i * this.tickSize);
 
      // Volume distribution — more volume near mid price
      // Level 0 (best) has most volume, tapers off deeper
      const volume = this._generateLevelVolume(i);
 
      levels.push({
        price: levelPrice,
        volume,
        side,
        level: i, // 0 = best price
      });
    }
 
    return levels;
  }
 
  /**
   * Update one side — keeps prices fresh, slightly randomizes volumes
   * @param {'bid'|'ask'} side
   * @param {number} bestPrice
   * @param {Array} previousLevels
   */
  _updateSide(side, bestPrice, previousLevels) {
    const isBid = side === "bid";
 
    return previousLevels.map((level, i) => {
      const levelPrice = isBid
        ? this._round(bestPrice - i * this.tickSize)
        : this._round(bestPrice + i * this.tickSize);
 
      // Slightly shift volume ±10% for realism
      const shift = 1 + (Math.random() - 0.5) * 0.2;
      const newVolume = Math.round(level.volume * shift);
      const { min, max } = this.volume;
      const clampedVol = Math.max(min, Math.min(max, newVolume));
 
      return {
        price: levelPrice,
        volume: clampedVol,
        side,
        level: i,
      };
    });
  }
 
  /**
   * Generate volume for a specific depth level
   * Levels closer to mid (lower index) get more volume
   * @param {number} levelIndex - 0 is best price
   */
  _generateLevelVolume(levelIndex) {
    const { min, max } = this.volume;
 
    // Taper factor — level 0 gets full range
    // level 9 gets ~30% of range
    const taper = Math.max(0.3, 1 - levelIndex * 0.07);
    const range = (max - min) * taper;
    const volume = Math.round(min + Math.random() * range);
 
    return Math.max(min, Math.min(max, volume));
  }
 
  /**
   * Round to configured precision
   */
  _round(value) {
    return parseFloat(value.toFixed(this.precision));
  }
}
 
module.exports = { OrderBook };