Skip to content
Mboum
How to Build a Custom Stock Charting Widget with Historical OHLCV JSON

A chart widget needs bars in time order, one row per bar with open, high, low, close and volume, and an API key that never reaches the browser. Mboum's v2 history endpoint returns the data in that shape. This tutorial builds a small page with candles, volume and an interval picker using TradingView's Lightweight Charts, with a tiny Node server between the page and Mboum.

Prerequisites

  • Node.js 18 or later. The code uses the built-in fetch and needs no npm packages.
  • A Mboum API key from mboum.com/pages/api.

The history endpoint

GET https://api.mboum.com/v2/markets/stock/history has weight 1. It takes ticker (or symbol), a required interval (1m, 5m, 15m, 30m, 1h, 1d, 1wk, 1mo and a few more), and limit from 1 to 1000, which defaults to 640. It accepts one ticker per request. body is a list ordered oldest to newest, with no duplicate times. Our check returned no null prices. The intervals and lookback windows are covered in the candles post. The last two daily rows for AAPL:

{
  "meta": {"version": "v2.0", "status": 200, "ticker": "AAPL", "interval": "1d"},
  "body": [
    {"timestamp": "2026-11-30", "timestamp_unix": 1796014800, "open": 359.045, "high": 359.44, "low": 352.11, "close": 354, "volume": 62214800},
    {"timestamp": "2026-12-01", "timestamp_unix": 1796101200, "open": 350.985, "high": 351.72, "low": 348.45, "close": 351.19, "volume": 38431274}
  ]
}

For daily and longer intervals, timestamp is a date string. For intraday intervals it is YYYY-MM-DD HH:MM in New York time. timestamp_unix is in seconds. The last bar is the period still in progress.

Step 1: a server that keeps the key private

The browser calls /candles on your server. The server adds the key, calls Mboum and passes the list through. Save it as server.js:

// server.js - Node 18+, no packages
const http = require("http");
const fs = require("fs");

const API_KEY = "YOUR_MBOUM_API_KEY"; // stays on the server, never in browser code
const INTERVALS = ["5m", "15m", "30m", "1h", "1d", "1wk", "1mo"];

function send(res, status, payload) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(payload));
}

http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");

  if (url.pathname === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    return res.end(fs.readFileSync("index.html"));
  }

  if (url.pathname === "/candles") {
    const ticker = (url.searchParams.get("ticker") || "AAPL").toUpperCase();
    const interval = url.searchParams.get("interval") || "1d";
    if (!/^[A-Z0-9.^-]{1,12}$/.test(ticker) || !INTERVALS.includes(interval)) {
      return send(res, 400, { error: "Bad ticker or interval" });
    }

    try {
      const api = new URL("https://api.mboum.com/v2/markets/stock/history");
      api.search = new URLSearchParams({ ticker, interval, limit: "300" });
      const r = await fetch(api, {
        headers: { Authorization: `Bearer ${API_KEY}`, Accept: "application/json" },
      });
      const data = await r.json();
      // HTTP 200 can still be a failure, so check the body too
      if (!r.ok || data.success === false || !Array.isArray(data.body)) {
        return send(res, 502, { error: data.message || "No data returned" });
      }
      return send(res, 200, data.body);
    } catch (err) {
      return send(res, 502, { error: "Upstream request failed" });
    }
  }

  res.writeHead(404);
  res.end();
}).listen(3000, () => console.log("http://localhost:3000"));

Step 2: the page

Lightweight Charts wants a unique, ascending time on every row, which the endpoint already provides. Intraday bars use timestamp_unix. Daily and longer bars use the date string. Save this as index.html next to the server:

<!doctype html>
<meta charset="utf-8">
<title>Candles</title>
<script src="https://unpkg.com/[email protected]/dist/lightweight-charts.standalone.production.js"></script>
<body style="margin:0;background:#0b1220;color:#e5e7eb;font-family:sans-serif">
<form id="form" style="padding:12px">
  <input id="ticker" value="AAPL" size="6">
  <select id="interval">
    <option>1d</option><option>1wk</option><option>1mo</option><option>1h</option><option>5m</option>
  </select>
  <button>Load</button> <span id="msg"></span>
</form>
<div id="chart" style="height:480px"></div>
<script>
const chart = LightweightCharts.createChart(document.getElementById("chart"), {
  autoSize: true,
  layout: { background: { color: "#0b1220" }, textColor: "#cbd5e1" },
  grid: { vertLines: { color: "#1e293b" }, horzLines: { color: "#1e293b" } },
  timeScale: { timeVisible: true },
});
const candles = chart.addSeries(LightweightCharts.CandlestickSeries, {
  upColor: "#22c55e", downColor: "#ef4444", borderVisible: false,
  wickUpColor: "#22c55e", wickDownColor: "#ef4444",
});
const volume = chart.addSeries(LightweightCharts.HistogramSeries, {
  priceFormat: { type: "volume" }, priceScaleId: "",
});
volume.priceScale().applyOptions({ scaleMargins: { top: 0.8, bottom: 0 } });

async function load(ticker, interval) {
  const res = await fetch(`/candles?ticker=${ticker}&interval=${interval}`);
  const body = await res.json();
  if (!res.ok) throw new Error(body.error);

  // Intraday bars need unix seconds. Daily and longer bars use the date string.
  const intraday = /^\d+[mh]$/.test(interval);
  const times = body.map(b => (intraday ? b.timestamp_unix : b.timestamp));

  candles.setData(body.map((b, i) => ({
    time: times[i], open: b.open, high: b.high, low: b.low, close: b.close,
  })));
  volume.setData(body.map((b, i) => ({
    time: times[i], value: b.volume,
    color: b.close >= b.open ? "#22c55e66" : "#ef444466",
  })));
  chart.timeScale().fitContent();
}

document.getElementById("form").onsubmit = async (e) => {
  e.preventDefault();
  const msg = document.getElementById("msg");
  msg.textContent = "";
  try {
    await load(ticker.value.trim(), interval.value);
  } catch (err) {
    msg.textContent = err.message;
  }
};
load("AAPL", "1d");
</script>

Run node server.js and open http://localhost:3000. Each load of the chart makes one request at weight 1.

The same data in Chart.js

Chart.js has no candlestick type without a plugin, so this version draws the close as a line. It reads the same /candles route:

<canvas id="c" height="120"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script>
fetch("/candles?ticker=AAPL&interval=1d")
  .then(res => res.json())
  .then(body => {
    new Chart(document.getElementById("c"), {
      type: "line",
      data: {
        labels: body.map(b => b.timestamp),
        datasets: [{ label: "AAPL close", data: body.map(b => b.close), borderColor: "#22c55e", pointRadius: 0 }],
      },
    });
  });
</script>

Best practices

  • Pick the right time field. Unix times display in UTC on the axis, so the 9:30 New York open appears at 13:30 or 14:30. Use the date string for daily bars to avoid time zones.
  • Treat the last bar as live. Polling every minute and calling candles.update() with the newest bar is cheaper than reloading 300 bars.
  • Cache on your server. Hold each ticker and interval pair for a short time so ten visitors do not cost ten requests.
  • Check the body. An unknown ticker returns HTTP 200 with "success": false and "No data returned". The server turns that into a 502 with a message the page can show. Send Accept: application/json so a bad parameter returns a JSON error, not an HTML page.

Next steps

Add an indicator line from the technical indicators endpoints, or set limit higher for longer histories. You can get a free key at mboum.com/pages/api, and every endpoint is described in the API documentation.

The data is for information only. It is not investment advice.