Atlaslog
Atlaslog / Examples / deck.gl / Business scenarios / Trade Event Stream
deck.gl · Business scenario

Trade Event Stream

20,000 trade events scroll 20 at a time within the canvas; a screen grid aggregates density and the latest 2,000 trades are overlaid as points, with pause and grid toggles.

Open standalone → Chinese notes All business examples
/demos/deckgl-nongis-finance-events.htmlLIVE
single HTML file · CDN dependencies onlyinterface labels are in Chinese

Business context

Trade event streams work like market monitoring and risk dashboards. The users are traders, risk staff and data product managers watching how executions cluster across price and time and when abnormal spikes occur. Data is tick-by-tick fills from the matching or order system, millions to tens of millions per day; dashboards usually keep a rolling window of the latest 20,000 and overlay a screen grid for density.

Raw fields are price, size, side and timestamp, so they are normalized into a [0,1] price-difference and time axis, then multiplied by canvas dimensions into pixel coordinates; a viewport change requires recomputing everything rather than patching one place. Cesium works in longitude and latitude and three.js needs a custom orthographic camera and conversions; OrthographicView at zoom 0 maps one unit to one pixel, and ScreenGridLayer supplies the screen-space aggregation.

A common trap is treating pixel coordinates as fixed: after a browser resize, points crowd to the left or spill past the bottom edge. Grid colors are comparable only under a fixed colorDomain, and changing the domain moves every hot spot. The scatter of the latest 2,000 trades is a sampled highlight and does not mean those 2,000 account for all the density; cluster positions are generated and reflect distribution shape, not real contracts.

How it works

Events are generated in normalized coordinates: five clusters carry weights of 0.30, 0.22, 0.20, 0.16 and 0.12, the first four being point clusters of radius 0.06–0.11 and the last a spread band 0.40 wide along x; jitter inside a cluster sums three uniform random numbers as an approximate normal, then multiplies by the canvas W/2 and H/2 into pixel coordinates. The buffer holds a fixed 20,000 slots with head pointing at the oldest event; each frame rewrites the cluster coordinates, side and pos of 20 slots and advances 20 positions, while new events are written into a 2,000-entry recent ring. Nothing is allocated and no array is shifted. ScreenGridLayer uses cellSizePixels 18, roughly 72×40 cells on a 1280×720 canvas, with colorDomain fixed at [0,26] so density thresholds do not shift when the window changes.

When the window resizes, all 20,000 events must be multiplied back through nx, ny by the new W/2, H/2, otherwise pixel coordinates still belong to the old canvas and points crowd left or overflow the bottom; the resize callback recomputes once and calls setProps once. deck.gl 9 COORDINATE_SYSTEM offers cartesian, lnglat, meter-offsets and lnglat-offsets but no PIXEL enum, so screen pixels rely on OrthographicView at zoom 0, where one unit equals one pixel; the view must not enable the controller, or panning and zooming will detach pixel coordinates from the canvas. ScreenGridLayer aggregates on the CPU by default in v9, and 20,000 projections per frame fit the budget; the grid re-aggregates through the frame number in updateTriggers, and changing array contents without triggering it leaves the picture frozen on the first frame.

SettingEffect
cellSizePixels: 18Screen grid cell of 18 px, independent of zoom
colorDomain: [0, 26]Fixed density ceiling so colors are not rescaled on resize
ring buffer of 20,000 slotsOverwrites the oldest events, avoiding the O(n) cost of array shift
updateTriggers: {getPosition: frame number}Forces re-aggregation and position recomputation while the data reference is unchanged

Note. On viewport changes, multiply normalized coordinates back into pixels before resetting data; never let pixel coordinates drift from the canvas size.

Source

demos/deckgl-nongis-finance-events.html
<!--
  示例:交易事件流
  要点:屏幕像素坐标下用环形缓冲滚动 2 万个事件,ScreenGridLayer(cellSizePixels 18) 聚合密度,ScatterplotLayer 只画最新 2000 个
  依赖:deck.gl 9.0 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>交易事件流</title>
<style>
  html,body{height:100%;margin:0;background:#0d1117}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
  .bar{position:relative;z-index:5;flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600}
  .bar label{display:flex;align-items:center;gap:5px;cursor:pointer}
  .bar input[type=checkbox]{accent-color:#4f9ef8}
  .bar input[type=range]{width:150px;accent-color:#4f9ef8}
  .bar button{font:inherit;font-size:12px;padding:3px 10px;border-radius:4px;cursor:pointer;
       border:1px solid #2f3947;background:#1d242e;color:#c9d3e0}
  .bar button:hover{background:#26303d}
  .bar button.on{background:#2c4a7a;border-color:#4f8ad6;color:#dfe9ff}
  .bar .sep{width:1px;height:18px;background:#2a313c;margin:0 4px}
  #cv{flex:1 1 auto;min-height:0;width:100%;display:block}
</style>
</head>
<body>
<div class="bar">
  <span>窗口 <b id="n">20,000</b> 条 · 每帧 +20 淘汰最旧 20</span>
  <span class="sep"></span>
  <label><input id="grid" type="checkbox" checked>显示网格</label>
  <button id="run" class="on">暂停</button>
  <span class="sep"></span>
  <span>屏幕像素坐标 · 1 单位 = 1 px</span>
</div>
<canvas id="cv"></canvas>
<script src="https://cdn.jsdelivr.net/npm/deck.gl@9.0.35/dist.min.js"></script>
<script>
(function () {
  'use strict';

  if (typeof deck === 'undefined') {
    document.body.innerHTML =
      '<div style="padding:24px;color:#ff8c74">deck.gl 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  function rng(seed) {
    var a = seed >>> 0;
    return function () {
      a = (a + 0x6D2B79F5) >>> 0;
      var t = Math.imul(a ^ (a >>> 15), 1 | a);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };
  }

  var N = 20000, RECENT = 2000, RATE = 20;
  var cv = document.getElementById('cv');
  var W = cv.clientWidth || 900;
  var H = cv.clientHeight || 600;
  var rand = rng(31415);
  var i;

  // 五个成交簇,前四个是点簇,最后一个是细长的价差带
  var CLUSTERS = [
    [-0.56, -0.20, 0.10, 0.08, 0.30],
    [-0.12, 0.32, 0.09, 0.07, 0.22],
    [0.24, -0.36, 0.11, 0.06, 0.20],
    [0.56, 0.26, 0.08, 0.09, 0.16],
    [0.02, -0.02, 0.40, 0.02, 0.12]
  ];

  function seedEvent(e) {
    var r = rand(), acc = 0, c = CLUSTERS[4];
    for (var k = 0; k < CLUSTERS.length; k++) {
      acc += CLUSTERS[k][4];
      if (r <= acc) { c = CLUSTERS[k]; break; }
    }
    var nx = c[0] + (rand() + rand() + rand() - 1.5) * c[2] * 3.2;
    var ny = c[1] + (rand() + rand() + rand() - 1.5) * c[3] * 3.2;
    e.nx = nx < -0.98 ? -0.98 : (nx > 0.98 ? 0.98 : nx);
    e.ny = ny < -0.98 ? -0.98 : (ny > 0.98 ? 0.98 : ny);
    e.side = rand() < 0.48 ? 1 : 0;
  }

  function layoutEvent(e) {
    e.pos[0] = e.nx * W * 0.5;
    e.pos[1] = e.ny * H * 0.5;
  }

  var events = new Array(N);
  for (i = 0; i < N; i++) {
    events[i] = { nx: 0, ny: 0, side: 0, pos: [0, 0, 0] };
    seedEvent(events[i]);
    layoutEvent(events[i]);
  }

  var recent = new Array(RECENT);
  for (i = 0; i < RECENT; i++) recent[i] = events[(N - RECENT + i) % N];

  var head = 0, rHead = 0, frameNo = 0, paused = false, showGrid = true;

  function tick() {
    for (var k = 0; k < RATE; k++) {
      var e = events[head];
      seedEvent(e);
      layoutEvent(e);
      recent[rHead] = e;
      rHead = (rHead + 1) % RECENT;
      head = (head + 1) % N;
    }
  }

  function buildLayers() {
    var layers = [];
    if (showGrid) {
      layers.push(new deck.ScreenGridLayer({
        id: 'event-grid',
        data: events,
        coordinateSystem: deck.COORDINATE_SYSTEM.CARTESIAN,
        getPosition: function (d) { return d.pos; },
        getWeight: 1,
        cellSizePixels: 18,
        colorDomain: [0, 26],
        colorRange: [
          [24, 40, 78, 90],
          [32, 96, 150, 150],
          [58, 160, 190, 185],
          [244, 198, 94, 205],
          [236, 96, 64, 225]
        ],
        opacity: 0.72,
        pickable: false,
        updateTriggers: { getPosition: frameNo }
      }));
    }
    layers.push(new deck.ScatterplotLayer({
      id: 'event-recent',
      data: recent,
      coordinateSystem: deck.COORDINATE_SYSTEM.CARTESIAN,
      getPosition: function (d) { return d.pos; },
      getFillColor: function (d) {
        return d.side ? [240, 104, 72, 225] : [86, 214, 168, 225];
      },
      getRadius: 1.8,
      radiusUnits: 'pixels',
      radiusMinPixels: 1,
      pickable: false,
      updateTriggers: { getPosition: frameNo }
    }));
    return layers;
  }

  // 屏幕像素空间:deck.gl 9 的 COORDINATE_SYSTEM 里没有 PIXEL 枚举,
  // 用 OrthographicView(zoom 0 时 1 单位 = 1 px,flipY 默认向下)承载像素坐标
  var deckgl = new deck.Deck({
    canvas: 'cv',
    width: '100%',
    height: '100%',
    views: new deck.OrthographicView({ id: 'screen', flipY: true }),
    initialViewState: { target: [0, 0, 0], zoom: 0 },
    controller: false,
    layers: buildLayers()
  });

  window.addEventListener('resize', function () {
    W = cv.clientWidth;
    H = cv.clientHeight;
    for (var k = 0; k < N; k++) layoutEvent(events[k]);
    deckgl.setProps({ layers: buildLayers() });
  });

  var runEl = document.getElementById('run');
  runEl.addEventListener('click', function () {
    paused = !paused;
    runEl.className = paused ? '' : 'on';
    runEl.textContent = paused ? '继续' : '暂停';
  });

  document.getElementById('grid').addEventListener('change', function () {
    showGrid = this.checked;
    deckgl.setProps({ layers: buildLayers() });
  });

  function loop() {
    if (!paused) {
      tick();
      frameNo++;
      deckgl.setProps({ layers: buildLayers() });
    }
    requestAnimationFrame(loop);
  }

  window.__deck = deckgl;
  requestAnimationFrame(loop);
})();
</script>
</body>
</html>
Language: this page is in English; the demo keeps Chinese interface labels and code comments. The Chinese page carries the full notes and the same runnable file.

More business examples

deck.gl · APIScreenGridLayer deck.gl · APIScatterplotLayer deck.gl · APICOORDINATE_SYSTEM