---
title: "HTX - new addition to Siebly SDKs"
description: "HTX still splits spot and derivatives across v1 and v2 REST paths, different base URLs, and separate WebSocket feeds."
canonical: "https://siebly.io/blog/htx-new-addition-to-siebly-sdks"
---

# HTX - new addition to Siebly SDKs

HTX still splits spot and derivatives across v1 and v2 REST paths, different base URLs, and separate WebSocket feeds.

## Technical Disclaimer

These articles are software engineering references for exchange API integrations. They are not financial, investment, legal, tax, compliance, or trading advice. Use public data, demo, testnet, or paper workflows first. Keep API credentials out of frontend code and disable withdrawal permissions for automation keys.

## Overview {#overview}

HTX still splits spot and derivatives across v1 and v2 REST paths, different base URLs, and separate WebSocket feeds. Rolling your own client means HMAC-SHA256 signing, timestamp sync, gzip handling, and keeping track of which endpoint version each call needs. That work adds up fast, especially when connections drop during volatile markets.

The [@siebly/htx-api](/sdk/htx/javascript) package brings HTX in line with the rest of the Siebly SDK family: TypeScript-first REST clients, typed request and response shapes, and the same WebSocket patterns you already use on Binance, OKX, and the others. You still own rate limiting and execution logic. The SDK handles connectivity, signing, and the plumbing.

## Key Takeaways {#key-takeaways}

- HTX spot and futures use different hosts and API versions. The SDK routes each method to the right path so you do not have to map that yourself.
- Install with `npm install @siebly/htx-api`. Use `SpotClient` for spot and `FuturesClient` for USDT-M and Coin-M derivatives.
- Private REST calls are signed automatically with HMAC-SHA256 (Signature Version 2) and Base64 encoding.
- For order execution over WebSocket, `WebsocketClient.sendWSAPIRequest()` gives you promise-based request/response handling instead of manual event correlation.
- Monitor `X-HB-RateLimit-Requests-Remain` and `X-HB-RateLimit-Requests-Expire` response headers and throttle in your own code. The SDK does not do that for you.



## Navigating the HTX API Ecosystem for Node.js Developers {#navigating-the-htx-api-ecosystem-for-nodejs-developers}

[HTX (formerly Huobi)](https://en.wikipedia.org/wiki/HTX_(cryptocurrency_exchange)) runs separate stacks for spot and derivatives. Spot public data often lives under paths like `/market/history/kline`, while trading goes through `/v1/order/...`. Account valuation and some newer endpoints use `/v2/...`. Futures and swaps sit on `api.hbdm.com` (or the AWS mirror `api.hbdm.vn`) with their own path prefixes such as `/linear-swap-api/v1/...` for USDT-margined contracts and `/api/v1/...` for coin-margined products.

The [@siebly/htx-api](/sdk/htx/javascript) package exposes two REST entry points:

- `SpotClient` for spot markets, margin, earn, sub-accounts, and transfers.
- `FuturesClient` for USDT-M linear swaps, coin-margined perpetuals, and delivery futures.

Both extend the same signing and error-handling layer used across Siebly SDKs. If you have worked with [binance](/sdk/binance/javascript), [okx-api](/sdk/okx/javascript), or [bybit-api](/sdk/bybit/javascript), the shape will feel familiar.

### Fragmented API Versions: v1 vs v2 {#fragmented-api-versions-v1-vs-v2}

v1 still carries most spot trading and market data. v2 covers newer account and reference endpoints. Futures have their own versioning under `/linear-swap-api/` and `/api/v1/`. You do not pick versions manually: each SDK method targets the correct path. `getKlines()` hits `/market/history/kline`, `submitOrder()` posts to `/v1/order/orders/place`, and `getAccountValuation()` calls `/v2/account/valuation`.

### The Role of SDKs in Systematic Trading {#the-role-of-sdks-in-systematic-trading}

Siebly SDKs are built for production connectivity, not strategy logic. They sign requests, parse responses into typed objects, and keep WebSocket connections alive with heartbeats and reconnect handling. Rate limits, position sizing, and risk rules stay on your side. That separation is intentional: you control execution policy, the SDK controls protocol correctness.

Browse the full SDK directory at [siebly.io/sdk](/sdk).

## Mastering HTX Authentication and Request Signing {#mastering-htx-authentication-and-request-signing}

Every private HTX REST request needs a valid signature. The SDK builds the signing string as:

```text title="Imported example"
{HTTP_METHOD}\n{host}\n{path}\n{sorted_query_params}
```

It signs that string with HMAC-SHA256, Base64-encodes the result, and appends it as the `Signature` query parameter alongside `AccessKeyId`, `SignatureMethod`, `SignatureVersion`, and a UTC `Timestamp` in `YYYY-MM-DDThh:mm:ss` format. Get any of that wrong and HTX returns 401.

### Secure Secret Handling in Node.js {#secure-secret-handling-in-node-js}

Store keys in environment variables or a secrets manager. Never commit them. Create keys with the minimum permissions your workflow needs and disable withdrawals on any key used by automation.

### Automating the Signing Workflow {#automating-the-signing-workflow}

Pass credentials once at client construction. Every private method handles the rest.

```ts title="Imported example"
import { SpotClient } from "@siebly/htx-api";

const client = new SpotClient({
  apiKey: process.env.HTX_API_KEY,
  apiSecret: process.env.HTX_API_SECRET,
});
```

For AWS-hosted deployments, `SpotClient` defaults to `api-aws.huobi.pro`. `FuturesClient` defaults to `api.hbdm.vn`. Override with `baseUrlKey` if you need a different endpoint (for example `futuresAlt1` when the primary futures host is unreachable).

### Placing a Spot Order {#placing-a-spot-order}

Spot orders need an `account-id` from `getAccounts()`. Symbols are lowercase (`btcusdt`, not `BTCUSDT`).

```ts title="Imported example"
import { SpotClient } from "@siebly/htx-api";

const client = new SpotClient({
  apiKey: process.env.HTX_API_KEY,
  apiSecret: process.env.HTX_API_SECRET,
});

async function placeLimitBuy() {
  const accounts = await client.getAccounts();
  const spotAccount = accounts.data.find((a) => a.type === "spot");

  const result = await client.submitOrder({
"account-id": spotAccount!.id,
symbol: "btcusdt",
type: "buy-limit",
amount: "0.001",
price: "50000",
"client-order-id": client.generateNewOrderID(),
  });

  console.log("Order ID:", result.data);
}
```

Clock drift will break signatures. The SDK timestamps each request, but your server should stay synced with NTP. If you see timestamp errors, check system time before blaming the SDK.

## Transitioning to Awaitable WebSockets for HTX {#transitioning-to-awaitable-websockets-for-htx}

Event-driven WebSockets work fine for market data. They get awkward for trading. You send an order, register a listener, hope the right message arrives, and deal with out-of-order responses when multiple orders are in flight.

Siebly SDKs solve this with `sendWSAPIRequest()` on `WebsocketClient`. You pass the connection key, operation name, and parameters. The SDK assigns a request ID, sends the message, and returns a Promise that resolves when the matching response arrives. The same pattern exists on [Binance](https://github.com/tiagosiebler/binance), [OKX](https://github.com/tiagosiebler/okx-api), and [Gate.io](https://github.com/tiagosiebler/gateio-api). Here is how it looks on OKX:

```ts title="Imported example"
import { WebsocketAPIClient } from "okx-api";

const wsClient = new WebsocketAPIClient({
  apiKey: process.env.OKX_API_KEY,
  apiSecret: process.env.OKX_API_SECRET,
  apiPass: process.env.OKX_API_PASSPHRASE,
});

const result = await wsClient.submitNewOrder({
  instId: "BTC-USDT",
  tdMode: "cash",
  side: "buy",
  ordType: "limit",
  sz: "0.001",
  px: "50000",
});

console.log("Order response:", result);
```

HTX follows the same architecture: `WebsocketClient` for streams, `sendWSAPIRequest()` for promise-based trading calls. For continuous market data, subscribe to channels the event-driven way.

### Awaitable vs. Event-Driven Workflows {#awaitable-vs-event-driven-workflows}

Use awaitable WebSocket calls when you need a definitive answer before moving on (place order, cancel, amend). Use event subscriptions for order book updates, fills, and balance changes. Mixing both on the same connection is normal.

### Reliability and Reconnection Strategies {#reliability-and-reconnection-strategies}

The SDK sends heartbeat pings and emits `reconnecting` and `reconnected` events when a connection drops. After a reconnect you should re-subscribe to any channels you care about and reconcile local state against a REST snapshot. For a broader look at how this fits into a trading system, see [Algorithmic Trading System Architecture in Node.js](/blog/algorithmic-trading-system-architecture-in-nodejs-a-2026-engineering-guide).



## Building Resilient Market Data Pipelines {#building-resilient-market-data-pipelines}

Public endpoints do not need authentication. Fetch klines, depth, and tickers with a plain `SpotClient` instance.

```ts title="Imported example"
import { SpotClient } from "@siebly/htx-api";

const client = new SpotClient();

async function fetchMarketSnapshot() {
  const [depth, klines, ticker] = await Promise.all([
client.getMarketDepth({ symbol: "btcusdt", depth: 20, type: "step0" }),
client.getKlines({ symbol: "btcusdt", period: "1min", size: 100 }),
client.getTicker({ symbol: "btcusdt" }),
  ]);

  console.log("Best bid:", depth.tick.bids[0]);
  console.log("Latest candle:", klines.data[klines.data.length - 1]);
  console.log("Last price:", ticker.tick.close);
}
```

HTX applies per-endpoint rate limits at the UID level. Response headers `X-HB-RateLimit-Requests-Remain` and `X-HB-RateLimit-Requests-Expire` tell you how many calls you have left in the current window and when it resets. Build your collector to read those headers and back off before you hit the wall.

For USDT-M futures market data:

```ts title="Imported example"
import { FuturesClient } from "@siebly/htx-api";

const futures = new FuturesClient();

const klines = await futures.getLinearSwapKlines({
  contract_code: "BTC-USDT",
  period: "1min",
  size: 100,
});
```

### Scalable Ingestion Architectures {#scalable-ingestion-architectures}

Run market data ingestion as a separate service from your execution engine. The SDK gives you typed REST and WebSocket clients for the collector. Your throttling logic sits above it. For pipeline design patterns, see [Siebly AI for Historical and Live Data Pipelines](/ai/historical-live-data-pipeline).

### Safety Boundaries and Simulations {#safety-boundaries-and-simulations}

Test on HTX's futures testnet (`testnet: true` in client options) or with paper workflows before going live. Model fees (base spot tier is around 0.20% maker/taker for regular users, but your tier may differ) and set hard limits on position size in your own code.

## Deploying Production-Ready HTX Integrations {#deploying-production-ready-htx-integrations}

Before production:

1. Keys in env vars, withdrawal disabled, least-privilege permissions.
2. Application-level rate limiting using HTX response headers.
3. Error handling for network timeouts and exchange maintenance responses.
4. State reconciliation after any WebSocket reconnect.

### USDT-M Futures Order Example {#usdt-m-futures-order-example}

```ts title="Imported example"
import { FuturesClient } from "@siebly/htx-api";

const futures = new FuturesClient({
  apiKey: process.env.HTX_API_KEY,
  apiSecret: process.env.HTX_API_SECRET,
});

const order = await futures.submitLinearSwapCrossOrder({
  contract_code: "BTC-USDT",
  direction: "buy",
  offset: "open",
  volume: 1,
  lever_rate: 5,
  order_price_type: "limit",
  price: 50000,
});

console.log("Futures order:", order.data);
```

Coin-margined perpetuals and delivery contracts are available through the same `FuturesClient` with their respective methods (`submitCoinMPerpOrder`, `submitCoinMDeliveryOrder`, and related endpoints).

### Optimization for AI Coding Agents {#optimization-for-ai-coding-agents}

Typed SDK methods give LLMs a schema to work against instead of raw API docs. Parameter names, required fields, and response shapes are defined in TypeScript. That cuts down on hallucinated field names when you use AI-assisted development. See [Siebly AI Prompt Frameworks](/ai) for workflow templates.

### Long-Term Maintenance and Updates {#long-term-maintenance-and-updates}

Exchange APIs change. HTX updates rate limits, adds endpoints, and deprecates old paths. Track SDK releases at [siebly.io/releases](/releases) instead of maintaining your own wrapper.

### The Full Siebly SDK Family {#the-full-siebly-sdk-family}

HTX joins a lineup that already covers the major centralized exchanges:

| Exchange | NPM Package | Quickstart |
| --- | --- | --- |
| Binance | [binance](/sdk/binance/javascript) | [siebly.io/sdk/binance/javascript](/sdk/binance/javascript) |
| OKX | [okx-api](/sdk/okx/javascript) | [siebly.io/sdk/okx/javascript](/sdk/okx/javascript) |
| Bybit | [bybit-api](/sdk/bybit/javascript) | [siebly.io/sdk/bybit/javascript](/sdk/bybit/javascript) |
| Gate.io | [gateio-api](/sdk/gate/javascript) | [siebly.io/sdk/gate/javascript](/sdk/gate/javascript) |
| Bitget | [bitget-api](/sdk/bitget/javascript) | [siebly.io/sdk/bitget/javascript](/sdk/bitget/javascript) |
| KuCoin | [kucoin-api](/sdk/kucoin/javascript) | [siebly.io/sdk/kucoin/javascript](/sdk/kucoin/javascript) |
| Kraken | [@siebly/kraken-api](/sdk/kraken/javascript) | [siebly.io/sdk/kraken/javascript](/sdk/kraken/javascript) |
| Coinbase | [coinbase-api](/sdk/coinbase/javascript) | [siebly.io/sdk/coinbase/javascript](/sdk/coinbase/javascript) |
| BitMart | [bitmart-api](/sdk/bitmart/javascript) | [siebly.io/sdk/bitmart/javascript](/sdk/bitmart/javascript) |
| HTX | [@siebly/htx-api](/sdk/htx/javascript) | [siebly.io/sdk](/sdk) |

Same architecture everywhere: REST clients, `WebsocketClient` for streams, promise-based WebSocket API calls where the exchange supports them.

## Streamlining Your HTX Integration Strategy {#streamlining-your-htx-integration-strategy}

You do not need to maintain signing boilerplate or juggle v1 and v2 URL maps by hand. Install [@siebly/htx-api](/sdk/htx/javascript), wire up `SpotClient` and `FuturesClient`, and put your effort into execution logic and data pipelines instead of protocol details.

[Get started with the Siebly HTX SDK](/sdk).

## Frequently Asked Questions {#frequently-asked-questions}

### How do I handle HTX API rate limits in Node.js? {#how-do-i-handle-htx-api-rate-limits-in-node-js}

Implement throttling in your application. The SDK does not rate-limit for you. Read `X-HB-RateLimit-Requests-Remain` and `X-HB-RateLimit-Requests-Expire` from responses and slow down before you exhaust the quota. Limits are per UID and vary by endpoint (spot order placement is 100 requests per 2 seconds, for example).

### What is the difference between HTX v1 and v2 APIs? {#what-is-the-difference-between-htx-v1-and-v2-apis}

v1 handles most spot trading and market data. v2 covers newer account and reference endpoints. Futures use their own versioned paths under `/linear-swap-api/` and `/api/v1/`. The SDK methods map to the correct version automatically.

### Is the Siebly HTX SDK compatible with TypeScript? {#is-the-siebly-htx-sdk-compatible-with-typescript}

Yes. [@siebly/htx-api](/sdk/htx/javascript) ships with full type declarations for requests and responses. Your editor gets autocomplete and compile-time checks on every method.

### How do I sign private requests for the HTX REST API? {#how-do-i-sign-private-requests-for-the-htx-rest-api}

You do not sign them manually. Pass `apiKey` and `apiSecret` to the client constructor. The SDK builds the Signature Version 2 string, signs with HMAC-SHA256, and Base64-encodes the result on every private call.

### Does the Siebly SDK handle WebSocket reconnections automatically? {#does-the-siebly-sdk-handle-websocket-reconnections-automatically}

The SDK manages heartbeats and will attempt to reconnect dropped sockets. You are responsible for re-subscribing to channels and verifying account state after a reconnect.

### Can I use the HTX SDK for futures and swap trading? {#can-i-use-the-htx-sdk-for-futures-and-swap-trading}

Yes. `FuturesClient` covers USDT-M linear swaps, coin-margined perpetuals, and delivery futures. Methods are grouped by product type and margin mode (isolated vs cross).

### How do I securely store my HTX API keys for a Node.js app? {#how-do-i-securely-store-my-htx-api-keys-for-a-node-js-app}

Environment variables or a secrets manager. Never hard-code keys. Disable withdrawals. Grant only the permissions your automation actually needs.

### What is an awaitable WebSocket and why should I use it? {#what-is-an-awaitable-websocket-and-why-should-i-use-it}

It lets you `await` a WebSocket request the same way you would a REST call. The SDK tracks request IDs and resolves a Promise when the exchange responds. No manual event correlation, fewer race conditions when placing orders.

## Related articles

- [Evaluating a Production Ready Crypto Trading SDK for Node.js and TypeScript](/blog/evaluating-a-production-ready-crypto-trading-sdk-for-nodejs-and-typescript)
- [Using proxy with Siebly SDKs](/blog/using-proxy-with-siebly-sdks)
- [Stream Real-Time Crypto Market Data with TypeScript SDKs](/blog/stream-real-time-crypto-market-data-with-typescript-sdks)


## Related Siebly Resources

- [Binance JavaScript SDK](/sdk/binance/javascript)
- [Bybit JavaScript SDK](/sdk/bybit/javascript)
- [OKX JavaScript SDK](/sdk/okx/javascript)
- [Siebly SDK directory](/sdk)
- [Siebly AI Prompt Framework & Skills](/ai)
