
Security News
Crates.io Implements Trusted Publishing Support
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
gateio-api
Advanced tools
Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.
Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST APIs and WebSockets:
reconnected
event when dropped connection is restored.npm install --save gateio-api
Check out my related JavaScript/TypeScript/Node.js projects:
Most methods accept JS objects. These can be populated using parameters specified by gateio's API documentation.
This project uses typescript. Resources are stored in 2 key structures:
Create API credentials
To use any of Gate.com's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the RestClient
:
const { RestClient } = require('gateio-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const client = new RestClient({
apiKey: API_KEY,
apiSecret: PRIVATE_KEY,
});
client
.getSpotTicker()
.then((result) => {
console.log('all spot tickers result: ', result);
})
.catch((err) => {
console.error('spot ticker error: ', err);
});
client
.getSpotOrders({
currency_pair: 'BTC_USDT', // Specify the currency pair
status: 'open', // Specify the status of the orders to fetch
})
.then((result) => {
console.log('getSpotOrders result: ', result);
})
.catch((err) => {
console.error('getSpotOrders error: ', err);
});
See RestClient for further information, or the examples for lots of usage examples.
All available WebSockets can be used via a shared WebsocketClient
. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see WS_KEY_MAP for a list of supported values).
Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the examples folder on GitHub.
Data events are emitted from the WebsocketClient via the update
event, see example below:
const { WebsocketClient } = require('gateio-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const wsConfig = {
apiKey: API_KEY,
apiSecret: PRIVATE_KEY,
/*
The following parameters are optional:
*/
// Livenet is used by default, use this to enable testnet:
// useTestnet: true
// how long to wait (in ms) before deciding the connection should be terminated & reconnected
// pongTimeout: 1000,
// how often to check (in ms) that WS connection is still alive
// pingInterval: 10000,
// how long to wait before attempting to reconnect (in ms) after connection is closed
// reconnectTimeout: 500,
// config options sent to RestClient (used for time sync). See RestClient docs.
// restOptions: { },
// config for axios used for HTTP requests. E.g for proxy support
// requestOptions: { }
};
const ws = new WebsocketClient(wsConfig);
/**
* Subscribing to data:
**/
const userOrders = {
topic: 'spot.orders',
payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
};
const userTrades = {
topic: 'spot.usertrades',
payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
};
const userPriceOrders = {
topic: 'spot.priceorders',
payload: ['!all'],
};
// subscribe to multiple topics at once
ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4');
// and/or subscribe to individual topics on demand
ws.subscribe(
{
topic: 'spot.priceorders',
payload: ['!all'],
},
'spotV4',
);
// Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above)
ws.subscribe('spot.balances', 'spotV4');
/**
* Handling events:
**/
// Listen to events coming from websockets. This is the primary data source
ws.on('update', (data) => {
console.log('data', data);
});
// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics)
ws.on('open', ({ wsKey, event }) => {
console.log('connection open for websocket with ID: ' + wsKey);
});
// Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic)
ws.on('response', (response) => {
console.log('response', response);
});
// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected.
ws.on('close', () => {
console.log('connection closed');
});
// Optional: listen to internal exceptions. Useful for debugging if something weird happens
ws.on('exception', (data) => {
console.error('exception: ', data);
});
// Optional: Listen to raw error events.
ws.on('error', (err) => {
console.error('ERR', err);
});
See WebsocketClient for further information and make sure to check the examples folder for much more detail.
Gate.com supports sending requests (commands) over an active WebSocket connection. This is called the WebSocket API.
The WebSocket API is available through two approaches, depending on individual preference:
The WebSocket API is available in the WebsocketClient via the sendWSAPIRequest(wsKey, channel, params)
method.
Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design.
client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API exception for channel', channel, e))
, fire and forget, don't use awaitclient.on('exception', cb)
and client.on('response', cb)
const result = await client.sendWSAPIRequest(wsKey, channel, params)
, which returns a promiseThe WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to sendWSAPIRequest(...)
, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the RestClient).
It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection.
Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets.
const { WebsocketAPIClient } = require('gateio-api');
const API_KEY = 'xxx';
const API_SECRET = 'yyy';
async function start() {
// Make an instance of the WS API Client
const wsClient = new WebsocketAPIClient({
apiKey: API_KEY,
apiSecret: API_SECRET,
// Automatically re-auth WS API, if we were auth'd before and get reconnected
reauthWSAPIOnReconnect: true,
});
try {
// Connection will authenticate automatically before first request
// Make WebSocket API calls, very similar to a REST API:
/* ============ SPOT TRADING EXAMPLES ============ */
// Submit a new spot order
const newOrder = await wsClient.submitNewSpotOrder({
text: 't-my-custom-id',
currency_pair: 'BTC_USDT',
type: 'limit',
account: 'spot',
side: 'buy',
amount: '1',
price: '10000',
});
console.log('Order result:', newOrder.data);
// Cancel a spot order
const cancelOrder = await wsClient.cancelSpotOrder({
order_id: '1700664330',
currency_pair: 'BTC_USDT',
account: 'spot',
});
console.log('Cancel result:', cancelOrder.data);
// Get spot order status
const orderStatus = await wsClient.getSpotOrderStatus({
order_id: '1700664330',
currency_pair: 'BTC_USDT',
account: 'spot',
});
console.log('Order status:', orderStatus.data);
/* ============ FUTURES TRADING EXAMPLES ============ */
// Submit a new futures order
const newFuturesOrder = await wsClient.submitNewFuturesOrder({
contract: 'BTC_USDT',
size: 10,
price: '31503.28',
tif: 'gtc',
text: 't-my-custom-id',
});
console.log('Futures order result:', newFuturesOrder.data);
// Cancel a futures order
const cancelFuturesOrder = await wsClient.cancelFuturesOrder({
order_id: '74046514',
});
console.log('Cancel futures order result:', cancelFuturesOrder.data);
// Get futures order status
const futuresOrderStatus = await wsClient.getFuturesOrderStatus({
order_id: '74046543',
});
console.log('Futures order status:', futuresOrderStatus.data);
} catch (e) {
console.error('WS API Error:', e);
}
}
start();
For more detailed examples using any approach, refer to the examples folder (e.g. ws-api-client.ts).
Pass a custom logger which supports the log methods silly
, debug
, notice
, info
, warning
and error
, or override methods from the default logger as desired.
const { WebsocketClient, DefaultLogger } = require('gateio-api');
// Disable all logging on the silly level
DefaultLogger.silly = () => {};
const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger);
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
FAQs
Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.
The npm package gateio-api receives a total of 253 weekly downloads. As such, gateio-api popularity was classified as not popular.
We found that gateio-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
Research
/Security News
Undocumented protestware found in 28 npm packages disrupts UI for Russian-language users visiting Russian and Belarusian domains.
Research
/Security News
North Korean threat actors deploy 67 malicious npm packages using the newly discovered XORIndex malware loader.