← All articles

Which position paid that funding fee? Track Gate futures funding per contract in Node.js/TS

If you trade several Gate USDT perpetuals at once, you will want to know which position each funding payment belongs to. The futures.balances WebSocket channel tells you that a funding payment happened, but at the time of writing it does not tell you for which contract. The REST account book does.

This post shows how to total funding per contract in Node.js and TypeScript with gateio-api (v1.6.9 at the time of writing): backfill and totals from getFuturesAccountBook(), and futures.balances as a live signal to re-read it.

What you see on the WebSocket

A user asked about this in the Gate API Telegram group. They reported that since about 18 November 2026 20:00 UTC, funding updates (type: "fund") on the USDT futures.balances channel have text: "funding" instead of the contract name, such as PROMPT_USDT, and that the message has no contract field.

Gate staff replied on 24 November 2026 that this is expected. They also said they plan to add a contract field to the futures.balances message, and that they expected it to go live later that week. Until it ships and is documented, treat that field as optional.

This is the documented shape of a futures.balances update. Note the fields: balance, change, text, time, time_ms, type, user and currency. There is no contract and no record ID.

{
  "channel": "futures.balances",
  "event": "update",
  "time": 1541505434,
  "time_ms": 1541505434123,
  "result": [
    {
      "balance": 9.998739899488,
      "change": -0.000002074115,
      "text": "BTC_USDT:3914424",
      "time": 1547199246,
      "time_ms": 1547199246123,
      "type": "fee",
      "user": "211xxx",
      "currency": "btc"
    }
  ]
}

Why the account book is the better record

GET /futures/{settle}/account_book lists the same balance changes, and you can filter by type=fund. Each row has a contract field (Gate documents it for data after 2023-10-30) and an id, so you can attribute each payment and drop duplicates. Gate’s example response:

{
  "time": 1682294400.123456,
  "change": "0.000010152188",
  "balance": "4.59316525194",
  "text": "ETH_USD:6086261",
  "type": "fee",
  "contract": "ETH_USD",
  "trade_id": "1",
  "id": "1"
}

A few things to know from the docs:

  • from and to are Unix timestamps in seconds. time in the response is in seconds too, with a fractional part.
  • change and balance are strings in the REST response, and numbers in the WebSocket message.
  • The endpoint uses limit and offset paging. Gate’s general rule is a default limit of 100 and a maximum of 1000, unless an endpoint says otherwise.
  • If you also pass contract, only records after 2023-10-30 can be filtered by it.

In gateio-api this is RestClient.getFuturesAccountBook(). A one-off backfill of the last 7 days:

const rows = await rest.getFuturesAccountBook({
  settle: 'usdt',
  type: 'fund',
  from: Math.floor(Date.now() / 1000) - 7 * 24 * 60 * 60,
  limit: 1000,
});

for (const row of rows) {
  console.log(row.contract, row.change, row.time);
}

Totals per contract, kept up to date

The approach: the account book is the only source for totals. A fund update on futures.balances means “read the account book again”. After a reconnect, read it again too, because anything paid while the socket was down will only be in the account book.

import { FuturesAccountBookRecord, RestClient, WebsocketClient } from 'gateio-api';

const apiKey = process.env.GATE_API_KEY;
const apiSecret = process.env.GATE_API_SECRET;

const rest = new RestClient({ apiKey, apiSecret });
const ws = new WebsocketClient({ apiKey, apiSecret });

// Funding totals per contract, built only from account book rows.
const fundingByContract = new Map<string, number>();
const seenIds = new Set<string>();
let cursorSec = Math.floor(Date.now() / 1000) - 7 * 24 * 60 * 60; // 7 days back

function addFundingRow(row: FuturesAccountBookRecord) {
  if (seenIds.has(row.id)) return;
  seenIds.add(row.id);

  // `contract` is optional in the response, so keep a bucket for rows without it.
  const contract = row.contract || 'unknown';
  const prev = fundingByContract.get(contract) ?? 0;
  fundingByContract.set(contract, prev + Number(row.change));

  cursorSec = Math.max(cursorSec, Math.floor(row.time));
}

async function syncFunding(reason: string) {
  const limit = 1000;
  // Re-read a little before the newest row we have. Duplicates are dropped by id.
  const from = cursorSec - 60;
  const to = Math.floor(Date.now() / 1000);

  for (let offset = 0; ; offset += limit) {
    const page = await rest.getFuturesAccountBook({
      settle: 'usdt',
      type: 'fund',
      from,
      to,
      limit,
      offset,
    });
    page.forEach(addFundingRow);
    if (page.length < limit) break;
  }

  console.log('Funding synced after', reason, Object.fromEntries(fundingByContract));
}

let syncTimer: ReturnType<typeof setTimeout> | undefined;
let syncRunning: Promise<void> = Promise.resolve();

// Funding settles for many contracts at once, so batch the REST reads.
function scheduleSync(reason: string, delayMs = 3000) {
  if (syncTimer) clearTimeout(syncTimer);
  syncTimer = setTimeout(() => {
    syncTimer = undefined;
    syncRunning = syncRunning
      .then(() => syncFunding(reason))
      .catch((e) => {
        console.error('Funding sync failed, retrying', e);
        scheduleSync('retry', 10_000);
      });
  }, delayMs);
}

interface WsBalanceRow {
  type: string;
  change: number;
  text: string;
  time_ms: number;
  contract?: string; // Not sent today. Gate says it plans to add it.
}

ws.on('update', (msg) => {
  if (msg?.channel !== 'futures.balances' || !Array.isArray(msg.result)) {
    return;
  }

  const fundingRows = (msg.result as WsBalanceRow[]).filter(
    (row) => row.type === 'fund',
  );
  if (!fundingRows.length) return;

  for (const row of fundingRows) {
    // Use the contract for live display once Gate sends it.
    console.log('Funding payment', row.contract ?? '(contract not sent)', row.change);
  }

  // The account book is the record you total from.
  scheduleSync('futures.balances fund update');
});

// Anything paid while the socket was down only shows up in the account book.
ws.on('reconnected', ({ wsKey }) => {
  if (wsKey === 'perpFuturesUSDTV4') scheduleSync('reconnected', 0);
});

ws.on('exception', (e) => console.error('ws exception', e));

// In case a row was not in the account book yet when a sync ran, check again later.
setInterval(() => scheduleSync('periodic', 0), 5 * 60_000);

async function start() {
  const { user_id } = await rest.getAccountDetail();

  await syncFunding('startup backfill');

  ws.subscribe(
    { topic: 'futures.balances', payload: [String(user_id)] },
    'perpFuturesUSDTV4',
  );
}

start().catch((e) => console.error('startup failed', e));

How it works

  • Startup. getAccountDetail() returns your user_id, which futures.balances needs as its payload, as a string. The backfill runs before the subscription.
  • Totals. addFundingRow() adds each row once, keyed by its id, to a per-contract total. Rows without contract go into an unknown bucket instead of being guessed.
  • Paging. syncFunding() reads from a minute before the newest row it has, up to now, 1000 rows at a time, until a page comes back short. Overlap is fine, because duplicates are dropped by id.
  • Live signal. Several positions can be paid funding at the same moment, so scheduleSync() waits 3 seconds and runs one REST read for the whole burst. Syncs run one after another, never in parallel, and a failed sync is retried.
  • Reconnects. The SDK reconnects and resubscribes futures.balances for you. On reconnected for perpFuturesUSDTV4, the code reads the account book straight away. In gateio-api, the event for a dropped connection is reconnect, followed by reconnected once it is back.
  • Periodic check. A sync every 5 minutes picks up any row that was not in the account book yet when an earlier sync ran.

When Gate adds the contract field

The WebSocket handler already reads row.contract if it is there, and logs (contract not sent) if it is not. That is enough for a live display, for example showing “BTC_USDT funding paid” as it happens. Keep the totals on the account book even then. The WebSocket rows have no ID, so you cannot safely merge them with REST rows, and they do not cover the time your socket was down.

Precision

The example adds amounts with Number, which is fine for a dashboard. For accounting, keep the original change strings and sum them with a decimal library.

Checklist

Symptom Likely cause Fix
Funding updates show text: "funding" and no contract Expected, according to Gate. A contract field is planned Attribute funding from getFuturesAccountBook({ settle: 'usdt', type: 'fund' }), which has contract on each row
Code that parsed the contract out of text stopped working Since about 18 November, funding rows have text: "funding", as reported in the Telegram thread Stop parsing text. Use the account book, and contract on the WebSocket once Gate ships it
Funding totals are too low after a disconnect Payments made while the socket was down Re-read the account book on reconnected
Funding totals are too high Overlapping reads counted twice Dedupe account book rows by id
Empty futures.balances stream Wrong payload or wrong connection Send your numeric user ID as a string in payload, on perpFuturesUSDTV4 for USDT perpetuals
  • Use the account book for totals, and the WebSocket as a trigger.
  • Treat contract on futures.balances as optional, even after Gate adds it.
  • Do not derive the contract from text.
  • Re-read after every reconnect.

Further reading