Skip to content

Node.js / JavaScript quickstart ​

Read a public btcusdt price with @siebly/htx-api. No API key or TypeScript compiler is needed. Prices are btcusdt last traded prices.

Use Node.js 24 and npm. If you prefer to start from a finished project, view the complete HTX Node.js example on GitHub.

The streaming example requires DecompressionStream support in your runtime.

Create the project ​

sh
mkdir htx-node-quickstart
cd htx-node-quickstart
npm init -y
npm install @siebly/htx-api

npm init creates package.json; npm install adds the current SDK release. You do not need to edit the package file for these examples.

Read a price ​

For a new project, create price.mjs with import. If your project uses require, choose price.cjs instead. Create one file; both request the price directly.

js
import { SpotClient } from '@siebly/htx-api';

const client = new SpotClient();
const response = await client.getTicker({ symbol: 'btcusdt' });
const price = response.tick.close;

if (!price) {
  throw new Error('No btcusdt price was returned.');
}

console.log('btcusdt REST price:', price);
js
const { SpotClient } = require('@siebly/htx-api');

async function main() {
  const client = new SpotClient();
  const response = await client.getTicker({ symbol: 'btcusdt' });
  const price = response.tick.close;

  if (!price) {
    throw new Error('No btcusdt price was returned.');
  }

  console.log('btcusdt REST price:', price);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run the file you created:

sh
node price.mjs
sh
node price.cjs

The result is the last traded price, for example:

text
btcusdt REST price: 65000.5

Stream a price (optional) ​

For a new project, create stream.mjs with import. If your project uses require, choose stream.cjs instead. Create one stream file; it closes the client after the first price or a failure.

js
import { WebsocketClient } from '@siebly/htx-api';
import process from 'node:process';

async function main() {
  const ws = new WebsocketClient();
  let timeout;
  let stopped = false;

  try {
    const firstPrice = new Promise((resolve, reject) => {
      timeout = setTimeout(() => {
        reject(new Error('No btcusdt update within 30 seconds.'));
      }, 30_000);

      ws.on('message', (message) => {
        if (Array.isArray(message) || message.ch !== 'market.btcusdt.detail') {
          return;
        }
        const tick = message.tick;
        if (!tick || typeof tick !== 'object' || !('close' in tick)) {
          return;
        }
        const price = tick.close;

        if (price) {
          resolve(String(price));
        }
      });
      ws.on('exception', reject);

      const subscription = Promise.resolve(ws.subscribe('market.btcusdt.detail', 'spotPublic'));
      subscription.catch(reject).finally(() => {
        if (stopped) {
          ws.closeAll();
        }
      });
    });

    console.log('btcusdt WebSocket price:', await firstPrice);
  } finally {
    stopped = true;
    clearTimeout(timeout);
    ws.closeAll();
    console.log('WebSocket closed.');
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
js
const { WebsocketClient } = require('@siebly/htx-api');
const process = require('node:process');

async function main() {
  const ws = new WebsocketClient();
  let timeout;
  let stopped = false;

  try {
    const firstPrice = new Promise((resolve, reject) => {
      timeout = setTimeout(() => {
        reject(new Error('No btcusdt update within 30 seconds.'));
      }, 30_000);

      ws.on('message', (message) => {
        if (Array.isArray(message) || message.ch !== 'market.btcusdt.detail') {
          return;
        }
        const tick = message.tick;
        if (!tick || typeof tick !== 'object' || !('close' in tick)) {
          return;
        }
        const price = tick.close;

        if (price) {
          resolve(String(price));
        }
      });
      ws.on('exception', reject);

      const subscription = Promise.resolve(ws.subscribe('market.btcusdt.detail', 'spotPublic'));
      subscription.catch(reject).finally(() => {
        if (stopped) {
          ws.closeAll();
        }
      });
    });

    console.log('btcusdt WebSocket price:', await firstPrice);
  } finally {
    stopped = true;
    clearTimeout(timeout);
    ws.closeAll();
    console.log('WebSocket closed.');
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run the matching file:

sh
node stream.mjs
sh
node stream.cjs

The script prints the first update, closes its WebSocket and exits. SDK connection logs may also appear:

text
btcusdt WebSocket price: 65001.2
WebSocket closed.

Troubleshooting ​

  • Use .mjs for import and .cjs for require. These Node.js module rules let you choose either format without configuring "type" in package.json.
  • If the SDK cannot be resolved, run the install command from the directory containing your program and package.json.
  • If a request fails or no update arrives within 30 seconds, check HTTPS and WSS access to the exchange from your network and region.
  • See Runtime setup for configuration details and WebSocket subscriptions for continuous subscriptions.

Built by Siebly. Open source SDKs for exchange APIs.