WebSocket API requests
Use WebsocketAPIClient for request/response operations over an authenticated connection. Use WebsocketClient subscriptions separately for ongoing fills and account changes.
Use await and try/catch just as you would with a REST API call. The SDK matches responses to requests and manages the WebSocket connection for you. Requests over a persistent WebSocket can offer lower overhead and latency, depending on the exchange, network and workload.
Read an existing Spot order
Set GATEIO_ORDER_ID in .env to an existing BTC_USDT exchange order ID. Save this as ws-api.ts beside the credential helper. Follow the compile instructions with ws-api.ts as the entry file:
import { WebsocketAPIClient } from 'gateio-api';
import { clientOptions, requiredEnv } from './authenticated-client.js';
async function main() {
const api = new WebsocketAPIClient({
...clientOptions,
attachEventListeners: false,
});
api.getWSClient().on('exception', () => {
console.error('WebSocket API request or connection failed.');
});
try {
const response = await api.getSpotOrderStatus({
currency_pair: 'BTC_USDT',
order_id: requiredEnv('GATEIO_ORDER_ID'),
account: 'spot',
});
console.log('Order state:', response.data.result);
} finally {
api.getWSClient().closeAll();
}
}
main().catch(() => {
console.error(
'Unable to read the order. Check its ID, credentials and environment.',
);
process.exitCode = 1;
});node --env-file=.env dist/ws-api.jsUse the same account and environment as the original order. This example only reads order status and closes its connection afterward.
Unlike REST methods, WebSocket API methods return an envelope. The operation's result is in response.data.result. Failed requests reject; batch results still require checking individual items. Avoid logging the full envelope or raw error because the SDK may attach signed request context.
Available commands
submitNewSpotOrder(),updateSpotOrder()andcancelSpotOrder()manage Spot orders.submitNewFuturesOrder()and the other futures methods use the USDT perpetual connection by default. Select the supported futures connection key when needed.getWSClient()exposes lifecycle events and shutdown.
The wrapper opens and authenticates connections as needed. To establish the Spot connection ahead of time, await getWSClient().connectWSAPI('spotV4'). For lower-level requests, use sendWSAPIRequest('spotV4', operation, params) on a WebsocketClient.
A long-running service should retain its client rather than reconnecting for each request. Set useTestnet: true on the wrapper for TestNet.
In-flight requests can reject when a connection closes, even if the exchange processed them. Resolve uncertain order outcomes before retrying a trading command.