Node.js & JavaScript SDK for the Gate.io REST APIs, WebSockets & WebSocket APIs. Fully typed and highly performant.
Installations
npm install gateio-api
Developer Guide
Typescript
Yes
Module System
ESM
Node Version
20.11.0
NPM Version
10.2.4
Score
63.1
Supply Chain
99.2
Quality
90.9
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Languages
TypeScript (99.6%)
JavaScript (0.3%)
Shell (0.09%)
Developer
Download Statistics
Total Downloads
6,585
Last Day
4
Last Week
26
Last Month
597
Last Year
6,400
GitHub Statistics
8 Stars
194 Commits
2 Forks
1 Watching
3 Branches
3 Contributors
Sponsor this package
Package Meta Information
Latest Version
1.1.2
Package Id
gateio-api@1.1.2
Unpacked Size
1.02 MB
Size
137.27 kB
File Count
311
NPM Version
10.2.4
Node Version
20.11.0
Publised On
10 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
6,585
Last day
-20%
4
Compared to previous day
Last week
-64.4%
26
Compared to previous week
Last month
-48%
597
Compared to previous month
Last year
8,433.3%
6,400
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Node.js & JavaScript SDK for Gate.io REST APIs, WebSockets & WebSocket API
Updated & performant JavaScript & Node.js SDK for the Gate.io REST APIs and WebSockets:
- Extensive integration with Gate.io REST APIs and WebSockets.
- TypeScript support (with type declarations for most API requests & responses).
- Gate.io REST APIs for Gate.io Spot, Margin, Perpetual Futures, Delivery Futures, Options & Announcements APIs.
- Strongly typed on most requests and responses.
- Extremely robust & performant JavaScript/Node.js Gate.io SDK.
- Actively maintained with a modern, promise-driven interface.
- Support for seamless API authentication for private Gate.io REST API and WebSocket calls.
- Gate.io Spot, Margin, Perpetual Futures, Delivery Futures & Options.
- Event driven messaging.
- Smart websocket persistence
- Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
- Automatically handle listenKey persistence and expiration/refresh.
- Emit
reconnected
event when dropped connection is restored.
- Websocket API for Gate.io Spot, Margin, Perpetual Futures & Delivery Futures.
- Automatic connectivity via existing WebsocketClient, just call sendWSAPIRequest to trigger a request.
- Automatic authentication, just call sendWSAPIRequest with channel & parameters.
- Choose between two interfaces for WS API communication:
- Event-driven interface, fire & forget via sendWSAPIRequest and receive async replies via wsClient's event emitter.
- Promise-driven interface, simply call and await sendWSAPIRequest for a REST-API-like behaviour with the WS API.
- Proxy support via axios integration.
- Active community support & collaboration in telegram: Node.js Algo Traders.
Installation
npm install --save gateio-api
Issues & Discussion
- Issues? Check the issues tab.
- Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
- Follow our announcement channel for real-time updates on X/Twitter
Related projects
Check out my related JavaScript/TypeScript/Node.js projects:
- Try my REST API & WebSocket SDKs:
- Try my misc utilities:
- Check out my examples:
Documentation
Most methods accept JS objects. These can be populated using parameters specified by gateio's API documentation.
- Gate.io API Documentation
- REST Endpoint Function List
- TSDoc Documentation (autogenerated using typedoc)
Structure
This project uses typescript. Resources are stored in 2 key structures:
- src - the whole connector written in typescript
- examples - some implementation examples & demonstrations. Contributions are welcome!
Usage
Create API credentials
REST API
To use any of Gate.io's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the RestClient
:
1const { RestClient } = require('gateio-api'); 2 3const API_KEY = 'xxx'; 4const PRIVATE_KEY = 'yyy'; 5 6const client = new RestClient({ 7 apiKey: API_KEY, 8 apiSecret: PRIVATE_KEY, 9}); 10 11client 12 .getSpotTicker() 13 .then((result) => { 14 console.log('all spot tickers result: ', result); 15 }) 16 .catch((err) => { 17 console.error('spot ticker error: ', err); 18 }); 19 20client 21 .getSpotOrders({ 22 currency_pair: 'BTC_USDT', // Specify the currency pair 23 status: 'open', // Specify the status of the orders to fetch 24 }) 25 .then((result) => { 26 console.log('getSpotOrders result: ', result); 27 }) 28 .catch((err) => { 29 console.error('getSpotOrders error: ', err); 30 });
See RestClient for further information, or the examples for lots of usage examples.
WebSockets
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:
1const { WebsocketClient } = require('gateio-api'); 2 3const API_KEY = 'xxx'; 4const PRIVATE_KEY = 'yyy'; 5 6const wsConfig = { 7 apiKey: API_KEY, 8 apiSecret: PRIVATE_KEY, 9 10 /* 11 The following parameters are optional: 12 */ 13 14 // Livenet is used by default, use this to enable testnet: 15 // useTestnet: true 16 17 // how long to wait (in ms) before deciding the connection should be terminated & reconnected 18 // pongTimeout: 1000, 19 20 // how often to check (in ms) that WS connection is still alive 21 // pingInterval: 10000, 22 23 // how long to wait before attempting to reconnect (in ms) after connection is closed 24 // reconnectTimeout: 500, 25 26 // config options sent to RestClient (used for time sync). See RestClient docs. 27 // restOptions: { }, 28 29 // config for axios used for HTTP requests. E.g for proxy support 30 // requestOptions: { } 31}; 32 33const ws = new WebsocketClient(wsConfig); 34 35/** 36 * Subscribing to data: 37 **/ 38 39const userOrders = { 40 topic: 'spot.orders', 41 payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], 42}; 43 44const userTrades = { 45 topic: 'spot.usertrades', 46 payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], 47}; 48 49const userPriceOrders = { 50 topic: 'spot.priceorders', 51 payload: ['!all'], 52}; 53 54// subscribe to multiple topics at once 55ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4'); 56 57// and/or subscribe to individual topics on demand 58ws.subscribe( 59 { 60 topic: 'spot.priceorders', 61 payload: ['!all'], 62 }, 63 'spotV4', 64); 65 66// Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above) 67ws.subscribe('spot.balances', 'spotV4'); 68 69/** 70 * Handling events: 71 **/ 72 73// Listen to events coming from websockets. This is the primary data source 74ws.on('update', (data) => { 75 console.log('data', data); 76}); 77 78// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) 79ws.on('open', ({ wsKey, event }) => { 80 console.log('connection open for websocket with ID: ' + wsKey); 81}); 82 83// Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic) 84ws.on('response', (response) => { 85 console.log('response', response); 86}); 87 88// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected. 89ws.on('close', () => { 90 console.log('connection closed'); 91}); 92 93// Optional: listen to internal exceptions. Useful for debugging if something weird happens 94ws.on('exception', (data) => { 95 console.error('exception: ', data); 96}); 97 98// Optional: Listen to raw error events. 99ws.on('error', (err) => { 100 console.error('ERR', err); 101});
See WebsocketClient for further information and make sure to check the examples folder for much more detail.
Websocket API
The WebsocketClient supports this exchange's Websocket API. There are two ways to use the WS API, depending on individual preference:
- event-driven:
- send requests via
client.sendWSAPIRequest(wsKey, channel, params)
, fire and forget, don't use await - handle async replies via event handlers on
client.on('exception', cb)
andclient.on('response', cb)
- send requests via
- promise-driven:
- send requests via
const result = await client.sendWSAPIRequest(wsKey, channel, params)
, which returns a promise - await each call
- use try/catch blocks to handle promise rejections
- send requests via
The below example demonstrates the promise-driven approach, which behaves similar to a REST API. For more detailed examples, refer to the examples folder (e.g the ws-private-spot-wsapi.ts example).
1const { WebsocketClient } = require('gateio-api'); 2 3const API_KEY = 'xxx'; 4const PRIVATE_KEY = 'yyy'; 5 6async function start() { 7 const client = new WebsocketClient({ 8 apiKey: API_KEY, 9 apiSecret: PRIVATE_KEY, 10 // Automatically re-auth WS API, if we were auth'd before and get reconnected 11 reauthWSAPIOnReconnect: true, 12 }); 13 14 /** 15 * Setup basic event handlers for core connectivity events. 16 * Note for this approach, the `response` and `update` events are not needed (but you can use them too/instead if you prefer). 17 **/ 18 19 // Successfully connected 20 client.on('open', (data) => { 21 console.log(new Date(), 'ws connected ', data?.wsKey); 22 }); 23 24 // Something happened, attempting to reconnect 25 client.on('reconnect', (data) => { 26 console.log(new Date(), 'ws reconnect: ', data); 27 }); 28 29 // Reconnect successful 30 client.on('reconnected', (data) => { 31 console.log(new Date(), 'ws reconnected: ', data); 32 }); 33 34 // Connection closed. If unexpected, expect reconnect -> reconnected. 35 client.on('close', (data) => { 36 console.error(new Date(), 'ws close: ', data); 37 }); 38 39 client.on('exception', (data) => { 40 console.error(new Date(), 'ws exception: ', data); 41 }); 42 43 client.on('authenticated', (data) => { 44 console.error(new Date(), 'ws authenticated: ', data); 45 }); 46 47 try { 48 /** 49 * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. 50 */ 51 52 // The WSKey identifies which connection this request is for. 53 // (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4") 54 const wsKey = 'spotV4'; 55 56 /** 57 * To authenticate, send an empty request to "spot.login". The SDK will handle all the parameters. 58 * 59 * By default (reauthWSAPIOnReconnect: true), if we get reconnected later on (e.g. connection temporarily lost), we will try to re-authenticate the WS API automatically when the connection is restored. 60 */ 61 console.log(new Date(), 'try authenticate'); 62 const loginResult = await client.sendWSAPIRequest(wsKey, 'spot.login'); 63 console.log(new Date(), 'authenticated!', loginResult); 64 65 /** 66 * For other channels, you should include any parameters for the request (the payload) in your call. 67 * 68 * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. Only the core request parameters are needed. 69 */ 70 console.log(new Date(), 'try get order status'); 71 const orderStatus = await client.sendWSAPIRequest( 72 wsKey, 73 'spot.order_status', 74 { 75 order_id: '600995435390', 76 currency_pair: 'BTC_USDT', 77 }, 78 ); 79 80 console.log(new Date(), 'orderStatus result!', orderStatus); 81 } catch (e) { 82 console.error(`WS API Error: `, e); 83 } 84} 85 86start();
Customise Logging
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.
1const { WebsocketClient, DefaultLogger } = require('gateio-api'); 2 3// Disable all logging on the silly level 4DefaultLogger.silly = () => {}; 5 6const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger);
Contributions & Thanks
Have my projects helped you? Share the love, there are many ways you can show your thanks:
- Star & share my projects.
- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler
- Have an interesting project? Get in touch & invite me to it.
- Or buy me all the coffee:
- ETH(ERC20):
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
- ETH(ERC20):
Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
Star History
No vulnerabilities found.
No security vulnerabilities found.
Other packages similar to gateio-api
gateio-nodejs-api
This service was created simply for GateIO spot API transactions. The heavily used processes were simplified and coded on a single page
@xfilecom/gateio-api
Gate.io API client for Node.js with TypeScript support
@xfilecom/gateio-api-client
Gate.io API client for Node.js with TypeScript support
smxt
A JavaScript library for cryptocurrency trading.