← All articles

Is that Binance candle closed? Don’t trust closeTime. Get final USDⓈ-M klines in Node.js/TS

Your strategy waits for a 5-minute USD-M candle to close, then acts on it. You call GET /fapi/v1/klines, see that closeTime is already in the past, and treat the row as done. On 1 December 2026, official Binance developer support said that is not enough: a candle whose closeTime has passed can still show its last pre-close values until the next refresh. The REST payload has no closed flag and no version field. This post shows how to take a candle as final in Node.js and TypeScript with the binance SDK (v3.6.15 at the time of writing).

closeTime is not a close flag

The question was asked in the Binance Developer Community thread USD-M Futures REST kline finality and WebSocket gap recovery, opened on 25 November 2026, about ordinary traded-price 5-minute klines on BTCUSDT perpetual futures. Official Binance developer support replied twice on 1 December 2026. The follow-up confirms it is an official developer-support response, and that for anything contractually binding the official API docs and the Futures changelog remain the source of record.

GET /fapi/v1/klines returns a snapshot. “A candle whose closeTime has passed can still reflect its last pre-close values until the next fetch/refresh cycle completes.” There is no documented finalization delay and no SLA. A short lag of seconds is typical, but it is not guaranteed and should not be used as a fixed constant.

Open the WebSocket kline stream before, or in parallel with, your REST queries. Treat a candle as final once the stream delivers it with k.x = true, or once REST returns the subsequent candle (“a candle is only returned as closed once the next interval has begun”). The follow-up is explicit that the subsequent-REST-candle rule is “a recommended operational practice, not a documented guarantee.” For reliable 5-minute validation, “use WS k.x = true as the primary finality signal, use sequenced REST as reconciliation, and never rely on closeTime < serverTime alone or on a fixed delay.” Both sources should converge on the same final candle. A transient difference immediately after close is normal, because the WebSocket publishes the final candle as it closes and REST lags.

closeTime itself is well defined: it is the next open time minus 1 ms, aligned to a UTC grid. For the 5-minute interval that is openTime + 299,999 ms. That identity is a documented guarantee for this instrument class. What you should not do is treat that timestamp as a finality flag.

Once a symbol has begun trading, an interval with no trades is still returned as a flat candle: open, high and low equal the previous close, with volume = 0 and number of trades 0. During recovery, each openTime should equal the previous openTime plus one interval; a gap is missing data that must be re-fetched, not assumed. That describes normal continuous trading only. During maintenance, trading halts or suspensions, and contract lifecycle events, candles may be absent rather than flat. Do not back-fill those gaps. Check the maintenance schedule and the symbol’s status.

The structural rules apply to USD-M trade-price klines in general, but do not assume uniform behaviour. BTCUSDT and ETHUSDT trade continuously, while XAUUSDT and XAGUSDT are commodity-linked and may have different sessions, maintenance and lifecycle events. Derive per-symbol schedules from exchangeInfo. There is also no official revision notification or version identifier on the REST payload, so settled candles do not carry a formal versioned-finality guarantee. Daily archives on data.binance.vision can be used as a cross-check, but they may themselves be updated, and there is no revision-diff feed.

Question Documented guarantee? Practice
Final once closeTime is in the past No Wait for k.x = true, or for the next REST candle
Fixed finalization delay No SLA Do not wait a fixed number of seconds
REST matches the WS final candle Expected, not simultaneous Reconcile; treat WS as primary
5m closeTime is openTime + 299,999 ms Yes Use the UTC grid; do not use this as a close flag
No-trade interval is a flat candle Yes, after the first trade, during continuous trading Gap-check openTimes; do not invent candles across a halt

Do it in Node.js

In the binance SDK, USDMClient.getKlines() is GET /fapi/v1/klines. With beautify: true, WebsocketClient.subscribeKlines(symbol, '5m', 'usdm') delivers beautified klines on formattedMessage. The isWsFormattedKline() type guard narrows the event, and msg.kline.final is the beautified name for k.x. These are public market-data endpoints, so no API key is required.

The example below opens the stream first, takes msg.kline.final as the primary close signal, backfills from REST while dropping the last row, checks that each openTime steps by exactly five minutes, and re-fetches on the reconnected event. If a gap remains and the symbol’s status is not TRADING, it leaves the hole instead of inventing flat candles.

import {
  isWsFormattedKline,
  Kline,
  KlineInterval,
  USDMClient,
  WebsocketClient,
  WsMessageKlineFormatted,
} from 'binance';

const SYMBOL = 'BTCUSDT';
const INTERVAL: KlineInterval = '5m';
const INTERVAL_MS = 5 * 60 * 1000;

const rest = new USDMClient();
const ws = new WebsocketClient({ beautify: true });

interface Candle {
  openTime: number;
  closeTime: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  trades: number;
}

const closedByOpen = new Map<number, Candle>();

function fromRestRow(row: Kline): Candle {
  return {
    openTime: row[0],
    open: Number(row[1]),
    high: Number(row[2]),
    low: Number(row[3]),
    close: Number(row[4]),
    volume: Number(row[5]),
    closeTime: row[6],
    trades: row[8],
  };
}

function fromWsKline(k: WsMessageKlineFormatted['kline']): Candle {
  return {
    openTime: k.startTime,
    closeTime: k.endTime,
    open: k.open,
    high: k.high,
    low: k.low,
    close: k.close,
    volume: k.volume,
    trades: k.trades,
  };
}

/** REST rows except the last one. The last row may still be open, or just closed but not final. */
function dropUnfinalised(rows: Kline[]): Candle[] {
  if (rows.length < 2) {
    return [];
  }
  return rows.slice(0, -1).map(fromRestRow);
}

function firstGap(candles: Candle[]): { from: number; to: number } | null {
  for (let i = 1; i < candles.length; i++) {
    const expected = candles[i - 1].openTime + INTERVAL_MS;
    if (candles[i].openTime !== expected) {
      return { from: expected, to: candles[i].openTime };
    }
  }
  return null;
}

async function symbolIsTrading(symbol: string): Promise<boolean> {
  const info = await rest.getExchangeInfo();
  const found = info.symbols.find((s) => s.symbol === symbol);
  if (!found) {
    throw new Error(`unknown symbol ${symbol}`);
  }
  return found.status === 'TRADING';
}

async function loadClosedFromRest(startTime?: number): Promise<Candle[]> {
  const pull = () =>
    rest.getKlines({
      symbol: SYMBOL,
      interval: INTERVAL,
      limit: 1000,
      startTime,
    });

  let closed = dropUnfinalised(await pull());
  if (!firstGap(closed)) {
    return closed;
  }

  // One retry: during continuous trading a gap is missing data, not a flat candle.
  closed = dropUnfinalised(await pull());
  const gap = firstGap(closed);
  if (!gap) {
    return closed;
  }

  if (!(await symbolIsTrading(SYMBOL))) {
    // Maintenance, a halt, or a lifecycle event: do not invent candles.
    console.warn('kline gap while symbol is not TRADING; leaving it', gap);
    return closed;
  }

  throw new Error(
    `kline gap ${new Date(gap.from).toISOString()} -> ${new Date(gap.to).toISOString()}`,
  );
}

function acceptFinal(candle: Candle, source: 'ws' | 'rest'): void {
  const prev = closedByOpen.get(candle.openTime);
  // The WS k.x = true candle is the primary reference.
  if (prev && source === 'rest') {
    return;
  }
  closedByOpen.set(candle.openTime, candle);
}

function latestOpenTime(): number | undefined {
  let latest: number | undefined;
  for (const openTime of closedByOpen.keys()) {
    if (latest === undefined || openTime > latest) {
      latest = openTime;
    }
  }
  return latest;
}

export async function start(): Promise<void> {
  ws.on('formattedMessage', (msg) => {
    if (!isWsFormattedKline(msg)) {
      return;
    }
    if (msg.kline.symbol !== SYMBOL || msg.kline.interval !== INTERVAL) {
      return;
    }
    if (!msg.kline.final) {
      return;
    }
    acceptFinal(fromWsKline(msg.kline), 'ws');
  });

  ws.on('reconnecting', ({ wsKey }) => {
    console.warn('kline socket reconnecting', wsKey);
  });

  ws.on('reconnected', async ({ wsKey }) => {
    console.warn('kline socket reconnected, reconciling from REST', wsKey);
    const closed = await loadClosedFromRest(latestOpenTime());
    for (const candle of closed) {
      acceptFinal(candle, 'rest');
    }
  });

  // Open the stream first, then backfill. The SDK resubscribes after a drop.
  await ws.subscribeKlines(SYMBOL, INTERVAL, 'usdm');
  const initial = await loadClosedFromRest();
  for (const candle of initial) {
    acceptFinal(candle, 'rest');
  }
}

How it works

  • WebSocket first. new WebsocketClient({ beautify: true }) is required if you want formattedMessage, the isWsFormattedKline() guard, and msg.kline.final. Without beautify, the same flag is k.x on the raw message event. subscribeKlines('BTCUSDT', '5m', 'usdm') subscribes to the USD-M trade-price kline stream.
  • Primary signal. Only a payload that passes isWsFormattedKline() and has msg.kline.final === true is stored as closed from the stream. The beautified kline already has numeric open, high, low, close and volume, with startTime and endTime for the open and close timestamps.
  • REST as reconciliation. getKlines() returns Kline tuples: index 0 is openTime, 1 to 5 are open, high, low, close and volume (typed as numberInString), 6 is closeTime, and 8 is the number of trades. The code converts the prices and volume with Number(). It drops the last row, because that row may still be the open candle, or a just-closed candle that has not been refreshed to its final values. A candle is only kept from REST once a later candle exists in the same response. That is the recommended practice, not a guarantee, so a later WebSocket close still overwrites a REST value for the same openTime.
  • Gap checks. For the 5-minute interval, each kept openTime must equal the previous one plus 300,000 ms. If a hole remains after one retry and getExchangeInfo() shows the symbol’s status is not TRADING, the hole is left in place. Staff called that field symbolStatus; on the USD-M exchangeInfo symbol object in this SDK it is status (ContractStatus, for example TRADING or CLOSE). If the symbol is still TRADING, the code throws rather than inventing a flat candle, so you can re-fetch that range on purpose.
  • Reconnects. The SDK keeps the socket alive and, by default, resubscribes to the same klines after a drop. The reconnected event is the reliable point to reconcile anything missed while the socket was down. The handler re-reads REST from the latest stored openTime and fills only the gaps that WebSocket has not already closed.
  • The official example. examples/Rest/misc/tracking-candles.ts is a fuller in-memory candle store on the same APIs. Its REST backfill currently keeps rows with closeTime <= Date.now(), which is the test staff said is not sufficient, and its reconnected handler only logs. If you start from that example, replace the REST filter with “drop the last row until the next candle exists”, gap-check openTime, and re-fetch in the reconnected handler.

Checklist

Symptom Likely cause Fix
A REST candle whose closeTime has passed later changes The row was still a pre-close snapshot Do not use closeTime < serverTime. Wait for msg.kline.final, or for the next REST candle
You waited N seconds after closeTime and still saw a change There is no documented delay or SLA Do not use a fixed wait. Use k.x as the primary signal
A hole in 5-minute openTimes during a halt, filled with flat candles Flat zero-volume candles apply to continuous trading only Check getExchangeInfo() status and the maintenance schedule. Leave the gap
Missed closes after a socket drop The final k.x = true event was not received Re-fetch REST in the reconnected handler and drop the last row
msg.kline.final is always missing beautify was left off, so you are on the raw message event Set beautify: true, or read k.x on the raw payload
XAUUSDT or XAGUSDT candles missing around a session break Commodity-linked contracts may not trade continuously Take the schedule from exchangeInfo. Do not copy BTCUSDT assumptions
  • Use WebSocket k.x / msg.kline.final as the primary close signal.
  • On REST, drop the last row until the next candle exists.
  • Check that openTime steps by exactly one interval.
  • Do not back-fill gaps during maintenance, a halt, or a lifecycle event.
  • Re-fetch on reconnected.

Further reading