Class: WebsocketClient
Extends
BaseWebsocketClient<WsKey>
Constructors
Constructor
new WebsocketClient(options?: WSClientConfigurableOptions, logger?: object): WebsocketClient;Parameters
| Parameter | Type |
|---|---|
options? | WSClientConfigurableOptions |
logger? | { error: (...params: any) => void; info: (...params: any) => void; trace: (..._params: any) => void; } |
logger.error? | (...params: any) => void |
logger.info? | (...params: any) => void |
logger.trace? | (..._params: any) => void |
Returns
WebsocketClient
Inherited from
BaseWebsocketClient<WsKey>.constructor
Methods
assertIsAuthenticated()
assertIsAuthenticated(wsKey: WsKey): Promise<unknown>;Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
Returns
Promise<unknown>
Inherited from
BaseWebsocketClient.assertIsAuthenticated
close()
close(wsKey: WsKey, force?: boolean): void;Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
force? | boolean |
Returns
void
Inherited from
BaseWebsocketClient.close
closeAll()
closeAll(force?: boolean): void;Parameters
| Parameter | Type |
|---|---|
force? | boolean |
Returns
void
Inherited from
BaseWebsocketClient.closeAll
connectAll()
connectAll(): Promise<WSConnectedResult | undefined>[];Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library.
Returns array of promises that individually resolve when each connection is successfully opened.
Returns
Promise<WSConnectedResult | undefined>[]
Overrides
BaseWebsocketClient.connectAll
connectWSAPI()
connectWSAPI(wsKey: keyof WsAPIWsKeyTopicMap, skipAuth?: boolean): Promise<unknown>;Ensures the WS API connection is active and ready.
You do not need to call this, but if you call this before making any WS API requests, it can accelerate the first request (by preparing the connection in advance).
Parameters
| Parameter | Type |
|---|---|
wsKey | keyof WsAPIWsKeyTopicMap |
skipAuth? | boolean |
Returns
Promise<unknown>
emit()
emit<U extends keyof WSClientEventMap<TWSKey>>(event: U, ...args: Parameters<WSClientEventMap<WsKey>[U]>): boolean;Type Parameters
| Type Parameter |
|---|
U extends keyof WSClientEventMap<TWSKey> |
Parameters
| Parameter | Type |
|---|---|
event | U |
...args | Parameters<WSClientEventMap<WsKey>[U]> |
Returns
boolean
Inherited from
BaseWebsocketClient.emit
getTimeOffsetMs()
getTimeOffsetMs(): number;Returns
number
Inherited from
BaseWebsocketClient.getTimeOffsetMs
getWsStore()
getWsStore(): WsStore<WsKey, WsTopicRequest<string, any>>;Get the WsStore that tracks websockets & topics
Returns
WsStore<WsKey, WsTopicRequest<string, any>>
Inherited from
BaseWebsocketClient.getWsStore
isConnected()
isConnected(wsKey: WsKey): boolean;Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
Returns
boolean
Inherited from
BaseWebsocketClient.isConnected
on()
on<U extends keyof WSClientEventMap<TWSKey>>(event: U, listener: WSClientEventMap<WsKey>[U]): this;Type Parameters
| Type Parameter |
|---|
U extends keyof WSClientEventMap<TWSKey> |
Parameters
| Parameter | Type |
|---|---|
event | U |
listener | WSClientEventMap<WsKey>[U] |
Returns
this
Inherited from
BaseWebsocketClient.on
sendWSAPIRequest()
sendWSAPIRequest<TWSKey extends keyof WsAPIWsKeyTopicMap, TWSChannel extends
| SpotWSAPITopic
| FuturesWSAPITopic = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends
| string[]
| WSAPISpotOrderPlaceReq
| WSAPISpotOrderCancelReq
| WSAPISpotOrderCancelCPReq
| WSAPISpotOrderAmendReq
| WSAPISpotOrderStatusReq
| WSAPISpotOrderListReq
| WSAPIFuturesOrderPlaceReq
| WSAPIFuturesOrderCancelReq
| WSAPIFuturesOrderCancelCPReq
| WSAPIFuturesOrderAmendReq
| WSAPIFuturesOrderListReq
| WSAPIFuturesOrderStatusReq
| WSAPISpotOrderCancelIdsReq[]
| WSAPIFuturesOrderPlaceReq[]
| undefined = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse extends
| object
| WSAPIResponse<WSAPILoginResponse, "spot.login">
| WSAPIResponse<WSAPILoginResponse, "futures.login">
| WSAPIResponse<WSAPISpotOrder, "spot.order_place">
| WSAPIResponse<WSAPISpotOrder, "spot.order_cancel">
| WSAPIResponse<WSAPISpotOrderCancelIdsRespItem[], "spot.order_cancel_ids">
| WSAPIResponse<WSAPISpotOrder[], "spot.order_cancel_cp">
| WSAPIResponse<WSAPISpotOrder, "spot.order_amend">
| WSAPIResponse<WSAPISpotOrder, "spot.order_status">
| WSAPIResponse<WSAPISpotOrder[], "spot.order_list">
| WSAPIResponse<WSAPIFuturesOrder, "futures.order_place">
| WSAPIResponse<WSAPIFuturesOrderBatchPlaceRespItem[], "futures.order_batch_place">
| WSAPIResponse<WSAPIFuturesOrder, "futures.order_cancel">
| WSAPIResponse<WSAPIFuturesOrderCancelIdsRespItem[], "futures.order_cancel_ids">
| WSAPIResponse<WSAPIFuturesOrder[], "futures.order_cancel_cp">
| WSAPIResponse<WSAPIFuturesOrder, "futures.order_amend">
| WSAPIResponse<WSAPIFuturesOrder[], "futures.order_list">
| WSAPIResponse<WSAPIFuturesOrder, "futures.order_status"> = WsAPITopicResponseMap[TWSChannel]>(
wsKey: TWSKey,
channel: TWSChannel,
params?: TWSParams extends void ? undefined : TWSParams,
requestFlags?: WSAPIRequestFlags
): Promise<TWSAPIResponse>;Send a Websocket API event on a connection. Returns a promise that resolves on reply.
Returned promise is rejected if an exception is detected in the reply OR the connection disconnects for any reason (even if automatic reconnect will happen).
After a fresh connection, you should always send a login request first.
If you authenticated once and you're reconnected later (e.g. connection temporarily lost), the SDK will by default automatically:
- Detect you were authenticated to the WS API before
- Try to re-authenticate (up to 5 times, in case something (bad timestamp) goes wrong)
- If it succeeds, it will emit the 'authenticated' event.
- If it fails and gives up, it will emit an 'exception' event (type: 'wsapi.auth', reason: detailed text).
You can turn off the automatic re-auth WS API logic using reauthWSAPIOnReconnect: false in the WSClient config.
Type Parameters
Parameters
| Parameter | Type | Description |
|---|---|---|
wsKey | TWSKey | The connection this event is for (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4") |
channel | TWSChannel | The channel this event is for (e.g. "spot.login" to authenticate) |
params? | TWSParams extends void ? undefined : TWSParams | Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs. |
requestFlags? | WSAPIRequestFlags | - |
Returns
Promise<TWSAPIResponse>
Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response
Overrides
BaseWebsocketClient.sendWSAPIRequest
setTimeOffsetMs()
setTimeOffsetMs(newOffset: number): void;Parameters
| Parameter | Type |
|---|---|
newOffset | number |
Returns
void
Inherited from
BaseWebsocketClient.setTimeOffsetMs
subscribe()
subscribe(requests:
| string
| WsTopicRequest<string, any>
| (
| string
| WsTopicRequest<string, any>)[], wsKey: WsKey): void;Subscribe to one or more channels on the connection selected by the required second argument, wsKey. Pass a topic string or { topic, payload } object. Connection, private-request signing and resubscription are automatic. This method returns void; inspect subscription responses for acceptance or errors.
Parameters
| Parameter | Type |
|---|---|
requests | | string | WsTopicRequest<string, any> | ( | string | WsTopicRequest<string, any>)[] |
wsKey | WsKey |
Returns
void
Example
import { WebsocketClient } from 'gateio-api';
const ws = new WebsocketClient();
ws.on('response', (message) => {
console.log('Subscription response:', message);
});
ws.on('update', (message) => {
if (message.channel === 'spot.tickers') {
console.log('Ticker:', message.result);
}
});
ws.on('exception', () => {
console.error('WebSocket request or connection failed.');
});
ws.on('reconnect', () => {
console.log('Reconnecting; cached prices may be stale.');
});
ws.on('reconnected', () => {
console.log('Reconnected; waiting for fresh prices.');
});
ws.subscribe({ topic: 'spot.tickers', payload: ['BTC_USDT'] }, 'spotV4');
process.once('SIGINT', () => {
ws.closeAll();
});See
tryWsSend()
tryWsSend(
wsKey: WsKey,
wsMessage: string,
throwExceptions?: boolean
): void;Try sending a string event on a WS connection (identified by the WS Key)
Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
wsMessage | string |
throwExceptions? | boolean |
Returns
void
Inherited from
BaseWebsocketClient.tryWsSend
unsubscribe()
unsubscribe(requests:
| string
| WsTopicRequest<string, any>
| (
| string
| WsTopicRequest<string, any>)[], wsKey: WsKey): void;Remove subscriptions using the same topic, payload and required connection key passed to subscribe. Removed subscriptions are not restored after reconnecting.
Parameters
| Parameter | Type |
|---|---|
requests | | string | WsTopicRequest<string, any> | ( | string | WsTopicRequest<string, any>)[] |
wsKey | WsKey |
Returns
void