JavaScript and Node.js Quickstart
Details
Docs navigation
- Getting started: Quickstart, Authentication, Rate limits, Errors and retries
- Guides: Symbol formats, Timestamps and time zones, Pagination, Split and dividend adjustments, WebSocket streaming, Dataset downloads, Excel and Google Sheets, Changelog
- API reference: Stock bars, Stock trades and quotes, Snapshots and movers, Tickers, exchanges, calendar, Splits and dividends, Fundamentals and SEC filings, Options chain and Greeks, Options EOD, bars, OI, Forex, Crypto, Crypto derivatives, Futures bars and continuous, Settlements and COT, Indices, Economic data, Technical indicators
- SDKs: Python, JavaScript (you are here)
This page shows how to call our stock API from JavaScript in Node.js using the built-in fetch, with no extra packages for REST. It covers a reusable request helper, paging through long history, a batch snapshot for a watchlist and a WebSocket client for live trades. An official npm package is on the roadmap; until then, these snippets are all you need.
Early access. The API is planned and not live yet. The code reflects the v1 design.
Details
Steps
1. Check your Node version
node --version # v18 or newer has fetch built in
2. Keep the key in the environment
export MARKETDATA_API_KEY="paste-your-key-here"
Never put the key in code that runs in a browser. Anyone can read it from the network tab. Call our API from your server and pass results to the page.
3. Write a helper
Example, saved as md.mjs:
const API = "https://api.marketdata.co/v1";
const KEY = process.env.MARKETDATA_API_KEY;
export async function get(path, params = {}) {
const url = new URL(API + path);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v));
const res = await fetch(url, { headers: { Authorization: `Bearer ${KEY}` } });
const body = await res.json();
if (body.status === "error") {
const e = body.error;
throw new Error(`${res.status} ${e.code}: ${e.message} (${e.request_id})`);
}
return body;
}
export async function getAll(path, params = {}) {
const rows = [];
let cursor = null;
do {
const body = await get(path, { ...params, limit: 50000, ...(cursor ? { cursor } : {}) });
rows.push(...body.results);
cursor = body.next_cursor;
} while (cursor);
return rows;
}
4. Fetch daily bars
Example (JavaScript):
import { getAll } from "./md.mjs";
const bars = await getAll("/stocks/bars", { symbol: "AAPL", interval: "1d", start: "2025-01-01" });
const last = bars.at(-1);
console.log(last.date, last.close, last.adjusted_close);
5. Snapshot a watchlist in one call
Example (JavaScript):
import { get } from "./md.mjs";
const snap = await get("/stocks/snapshot", { symbols: "AAPL,MSFT,NVDA,TSLA" });
for (const s of snap.results) {
console.log(s.symbol.padEnd(6), s.last_price, `${s.change_percent}%`, s.is_delayed ? "(delayed)" : "");
}
Up to 250 symbols per call, and it counts as one request.
6. Stream live trades
Example (run npm install ws first):
import WebSocket from "ws";
const ws = new WebSocket("wss://stream.marketdata.co/v1/crypto");
ws.on("open", () => {
ws.send(JSON.stringify({ action: "auth", key: process.env.MARKETDATA_API_KEY }));
ws.send(JSON.stringify({ action: "subscribe", channel: "trades", symbols: ["BTC-USDT"], exchange: "binance" }));
});
ws.on("message", (frame) => {
for (const ev of JSON.parse(frame)) {
if (ev.type === "trade") console.log(ev.timestamp, ev.price, ev.size, ev.aggressor_side);
}
});
ws.on("close", () => setTimeout(() => process.exit(1), 1000)); // let a supervisor restart it
In production, reconnect with backoff and resubscribe. The WebSocket guide explains why.
7. Handle rate limits
Example (JavaScript):
async function withRetry(fn, tries = 5) {
for (let i = 0; i < tries; i++) {
try { return await fn(); }
catch (e) {
if (!/^(429|5\d\d) /.test(e.message)) throw e;
await new Promise((r) => setTimeout(r, 1000 * 2 ** i));
}
}
throw new Error("gave up after retries");
}
Watch out
Notes and gotchas
- Prices are JSON numbers, so they arrive as JavaScript doubles. That is fine for prices, but for summing large volumes over years use
BigIntor a decimal library if you need exact totals. - Timestamps are ISO 8601 strings in UTC.
new Date(ts)parses them, but it drops the nanoseconds on tick data. Keep the original string if order matters, and sort ties bysequence_number. fetchdoes not throw on HTTP errors. The helper above checksstatusin the body for that reason.- Node's
fetchhas no default timeout. Pass anAbortSignal.timeout(60000)for long pulls. - For TypeScript, the response field tables on each API reference page map one to one to interfaces.
Keep reading
Next steps
Details
Was this page useful?
[Yes] [No]
Want an official npm package? Tell us on the custom data form.