Gathering detailed insights and metrics for gateio-api
Gathering detailed insights and metrics for gateio-api
Gathering detailed insights and metrics for gateio-api
Gathering detailed insights and metrics for 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
smxt
A JavaScript library for cryptocurrency trading.
ninjaxt
NinjaXT is a comprehensive trading library designed for cryptocurrency platforms (currently supports Binance, Gateio and Bitmusa). It supports both spot and futures markets and is capable of handling both REST API calls and WebSocket streams.
Node.js & JavaScript SDK for the Gate.io REST APIs, WebSockets & WebSocket APIs. Fully typed and highly performant.
npm install gateio-api
Typescript
Module System
Node Version
NPM Version
63.1
Supply Chain
99.2
Quality
93.8
Maintenance
100
Vulnerability
100
License
TypeScript (99.6%)
JavaScript (0.3%)
Shell (0.09%)
Total Downloads
6,495
Last Day
9
Last Week
194
Last Month
763
Last Year
6,310
8 Stars
194 Commits
2 Forks
1 Watching
3 Branches
3 Contributors
Minified
Minified + Gzipped
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
Cumulative downloads
Total Downloads
Last day
-30.8%
9
Compared to previous day
Last week
-32.9%
194
Compared to previous week
Last month
-45.7%
763
Compared to previous month
Last year
7,502.4%
6,310
Compared to previous year
Updated & performant JavaScript & Node.js SDK for the 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.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.
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.
The WebsocketClient supports this exchange's Websocket API. There are two ways to use the WS API, depending on individual preference:
client.sendWSAPIRequest(wsKey, channel, params)
, 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 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();
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);
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.
No vulnerabilities found.
No security vulnerabilities found.