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 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
- 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. UseSpotClientfor spot andFuturesClientfor 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-RemainandX-HB-RateLimit-Requests-Expireresponse headers and throttle in your own code. The SDK does not do that for you.
Mastering HTX Authentication and Request Signing
Every private HTX REST request needs a valid signature. The SDK builds the signing string as:
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
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
Pass credentials once at client construction. Every private method handles the rest.
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
Spot orders need an account-id from getAccounts(). Symbols are lowercase (btcusdt, not BTCUSDT).
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
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, OKX, and Gate.io. Here is how it looks on OKX:
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
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
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.
Building Resilient Market Data Pipelines
Public endpoints do not need authentication. Fetch klines, depth, and tickers with a plain SpotClient instance.
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:
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
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.
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
Before production:
- Keys in env vars, withdrawal disabled, least-privilege permissions.
- Application-level rate limiting using HTX response headers.
- Error handling for network timeouts and exchange maintenance responses.
- State reconciliation after any WebSocket reconnect.
USDT-M Futures Order Example
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
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 for workflow templates.
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 instead of maintaining your own wrapper.
The Full Siebly SDK Family
HTX joins a lineup that already covers the major centralized exchanges:
Same architecture everywhere: REST clients, WebsocketClient for streams, promise-based WebSocket API calls where the exchange supports them.
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, wire up SpotClient and FuturesClient, and put your effort into execution logic and data pipelines instead of protocol details.
Frequently Asked Questions
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?
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?
Yes. @siebly/htx-api 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?
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?
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?
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?
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?
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
Continue from here