Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP endpoints #2

Merged
merged 42 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
94c8b40
feat(): Added Enpoints for "Withdrawal" and "Wallet"
JJ-Cro May 16, 2024
c62799f
feat(): Added subaccount and Margin endpoints
JJ-Cro May 18, 2024
a896543
feat(): added MarginUNI and FlashLoans endpoints
JJ-Cro May 19, 2024
f7d8802
feat(): Added futures, delivery and options endpoints
JJ-Cro May 19, 2024
9d70616
feat(): Added all endpoints
JJ-Cro May 19, 2024
71e33cd
chore(): refactoring types
JJ-Cro May 19, 2024
972eabd
chore(): refactoring types
JJ-Cro May 19, 2024
7cdabf7
feat(): auth for GET with params
tiagosiebler May 20, 2024
8633eb7
feat(): post auth with params
tiagosiebler May 20, 2024
ab711b7
chore(): Refactoring types
JJ-Cro May 20, 2024
1a88d55
Merge pull request #1 from tiagosiebler/authWithParams
tiagosiebler May 20, 2024
1db9de8
feat(): allow post requests to use query instead of body
tiagosiebler May 20, 2024
ecb4a3f
feat(): fix post req
tiagosiebler May 20, 2024
9361b3e
feat(): attempt to fix tsconfig
tiagosiebler May 20, 2024
543ac18
feat(): add test config
tiagosiebler May 20, 2024
440422d
chore(): Refactoring types
JJ-Cro May 20, 2024
ee51e35
Merge pull request #3 from tiagosiebler/querypost
tiagosiebler May 20, 2024
702a8c4
feat(): add auth tests
tiagosiebler May 20, 2024
a6dd846
feat(): add github ci + tests
tiagosiebler May 20, 2024
a88f594
chore(): Refactoring types
JJ-Cro May 20, 2024
6bf5b28
Merge branch 'jerko' of https://github.com/tiagosiebler/gateio-api in…
JJ-Cro May 20, 2024
93c4332
chore(): Refactoring types
JJ-Cro May 20, 2024
91c0c40
chore(): refactoring types
JJ-Cro May 20, 2024
3ce47e4
feat(): allow request to use query and/or string
tiagosiebler May 20, 2024
7308aa9
Merge branch 'jerko' into e2etests
tiagosiebler May 20, 2024
eece3c2
fix(): test fn name
tiagosiebler May 20, 2024
b2e8b2f
Merge pull request #4 from tiagosiebler/e2etests
tiagosiebler May 20, 2024
d894caf
chore(): refactor body to query mapping
tiagosiebler May 20, 2024
660ab71
chore(): refactoring types and requests
JJ-Cro May 20, 2024
f1a77ac
chore(): Refactoring types
JJ-Cro May 21, 2024
4b2b78a
chore(): refactoring types
JJ-Cro May 21, 2024
d3ee76e
chore(): refactoring types
JJ-Cro May 21, 2024
7be2a14
chore() : Refactoring futures types
JJ-Cro May 21, 2024
b318dbb
chore(): refactored all types and functions
JJ-Cro May 22, 2024
1d004e8
feat(): added examples, finished adding all types, minor changes
JJ-Cro May 22, 2024
68338ad
chore(): separated types per group, added rebates endpoints and types
JJ-Cro May 23, 2024
58c8d08
chore(): Separated all types into categories
JJ-Cro May 24, 2024
5d9a3e6
chore(): Fixed imports for types
JJ-Cro May 24, 2024
13b829f
feat(): prep work for gate WS client
tiagosiebler May 30, 2024
0010733
feat(): working public topics
tiagosiebler May 30, 2024
c39ddd7
chore(): readme updates
tiagosiebler May 30, 2024
2a31d3c
Merge pull request #5 from tiagosiebler/ws
tiagosiebler May 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# These are supported funding model platforms

github: [tiagosiebler, JJ-Cro] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 changes: 16 additions & 0 deletions .github/workflow-settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"EXCLUDE_MESSAGES": [
"update package version",
"update packages",
"update wp version",
"trigger workflow",
"update TOC"
],
"PROJECT": "Backlog",
"ISSUE_COLUMN": "To do",
"PR_COLUMN": "In progress",
"PR_BODY_TITLE": "## Changes",
"TOC_FOLDING": "1",
"TOC_MAX_HEADER_LEVEL": "3",
"TOC_TITLE": "Summary"
}
42 changes: 42 additions & 0 deletions .github/workflows/e2etest.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: 'Build & Test'

on: [push]

# on:
# # pull_request:
# # branches:
# # - "master"
# push:
# branches:

jobs:
build:
name: 'Build & Test'
runs-on: ubuntu-latest

steps:
- name: 'Checkout source code'
uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
registry-url: 'https://registry.npmjs.org/'
cache: 'npm'

- name: Install
run: npm ci --ignore-scripts

- name: Build
run: npm run build

- name: Test
run: npm run test
env:
API_KEY: ${{ secrets.API_KEY }}
API_SECRET: ${{ secrets.API_SECRET }}
PROXY_ENABLED: ${{ secrets.PROXY_ENABLED }}
PROXY_HOST: ${{ secrets.PROXY_HOST }}
PROXY_PASS: ${{ secrets.PROXY_PASS }}
PROXY_PORT: ${{ secrets.PROXY_PORT }}
PROXY_USER: ${{ secrets.PROXY_USER }}
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,7 @@ node_modules/
.cache
bundleReport.html
.history/
dist
coverage
localtest.sh

117 changes: 69 additions & 48 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,52 @@
# gateio-api
[![Tests](https://circleci.com/gh/tiagosiebler/gateio-api.svg?style=shield)](https://circleci.com/gh/tiagosiebler/gateio-api)
[![npm version](https://img.shields.io/npm/v/gateio-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1]

[![E2E Tests](https://github.com/tiagosiebler/gateio-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/gateio-api/actions/workflows/e2etest.yml)
[![npm version](https://img.shields.io/npm/v/gateio-api)][1]
[![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1]
[![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1]
[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/gateio-api)][1]
[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/gateio-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/gateio-api)

[1]: https://www.npmjs.com/package/gateio-api

WARNING: This package is still early beta, following the designs of my other connectors. If you want to stay informed when this may be ready for testing, please get in touch via telegram.

Node.js connector for the gateio APIs and WebSockets, with TypeScript & browser support.
Node.js & TypeScript SDK for Gate.io REST APIs and WebSockets.

## Installation

`npm install --save gateio-api`

## Issues & Discussion

- Issues? Check the [issues tab](https://github.com/tiagosiebler/gateio-api/issues).
- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram.

## Related projects
Check out my related projects:
- Try my connectors:
- [binance](https://www.npmjs.com/package/binance)
- [bybit-api](https://www.npmjs.com/package/bybit-api)
- [okx-api](https://www.npmjs.com/package/okx-api)
- [bitget-api](https://www.npmjs.com/package/bitget-api)
- [ftx-api](https://www.npmjs.com/package/ftx-api)

Check out my related JavaScript/TypeScript/Node.js projects:

- Try my API & WebSocket SDKs:
- [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api)
- [Binance Node.js SDK](https://www.npmjs.com/package/binance)
- [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api)
- [Gateio-api Nodejs SDK](https://www.npmjs.com/package/bitmart-api)
- [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api)
- [Bitmart-api Nodejs SDK](https://www.npmjs.com/package/bitmart-api)
- Try my misc utilities:
- [orderbooks](https://www.npmjs.com/package/orderbooks)
- [orderbooks node.js](https://www.npmjs.com/package/orderbooks)
- [accountstate](https://www.npmjs.com/package/accountstate)
- Check out my examples:
- [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples)

## Documentation

Most methods accept JS objects. These can be populated using parameters specified by gateio's API documentation.

- [Gate.io API Documentation](https://www.gate.io/docs/developers/apiv4/en/).

## Structure

This project uses typescript. Resources are stored in 3 key structures:

- [src](./src) - the whole connector written in typescript
- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release.
- [dist](./dist) - the packed bundle of the project for use in browser environments.
Expand All @@ -44,6 +55,7 @@ This project uses typescript. Resources are stored in 3 key structures:
---

# Usage

<!-- Create API credentials at okx
- [OKX my-api](https://www.okx.com/account/my-api) -->

Expand Down Expand Up @@ -111,7 +123,10 @@ client.getOrderBook({ symbol: 'BTCUSD' })
See [inverse-client.ts](./src/inverse-client.ts) for further information. -->

## WebSockets
Inverse, linear & spot WebSockets can be used via a shared `WebsocketClient`. However, make sure to make one instance of WebsocketClient per market type (spot vs inverse vs linear vs linearfutures):

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 - [WS_KEY_MAP](src/lib/websocket/websocket-util.ts).

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](./examples/) folder on GitHub.

```javascript
const { WebsocketClient } = require('gateio-api');
Expand All @@ -130,13 +145,6 @@ const wsConfig = {
// defaults to false == testnet. Set to true for livenet.
// livenet: true

// NOTE: to listen to multiple markets (spot vs inverse vs linear vs linearfutures) at once, make one WebsocketClient instance per market

// defaults to inverse:
// market: 'inverse'
// market: 'linear'
// market: 'spot'

// how long to wait (in ms) before deciding the connection should be terminated & reconnected
// pongTimeout: 1000,

Expand All @@ -151,22 +159,35 @@ const wsConfig = {

// config for axios used for HTTP requests. E.g for proxy support
// requestOptions: { }

// override which URL to use for websocket connections
// wsUrl: 'wss://stream.bytick.com/realtime'
};

const ws = new WebsocketClient(wsConfig);

const tickersRequestWithParams = {
topic: 'spot.tickers',
params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
};

const rawTradesRequestWithParams = {
topic: 'spot.trades',
params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
};

// subscribe to multiple topics at once
ws.subscribe(['position', 'execution', 'trade']);
ws.subscribe([tickersRequestWithParams, rawTradesRequestWithParams], 'spotV4');

// and/or subscribe to individual topics on demand
ws.subscribe('kline.BTCUSD.1m');
ws.subscribe(
{
topic: 'spot.trades',
params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
},
'spotV4',
);

// Listen to events coming from websockets. This is the primary data source
ws.on('update', data => {
console.log('update', data);
ws.on('update', (data) => {
console.log('data', data);
});

// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics)
Expand All @@ -175,7 +196,7 @@ ws.on('open', ({ wsKey, event }) => {
});

// Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic)
ws.on('response', response => {
ws.on('response', (response) => {
console.log('response', response);
});

Expand All @@ -184,21 +205,24 @@ 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.
// Note: responses to invalid topics are currently only sent in the "response" event.
ws.on('error', err => {
ws.on('error', (err) => {
console.error('ERR', err);
});
```


See [websocket-client.ts](./src/websocket-client.ts) for further information.

Note: for linear websockets, pass `linear: true` in the constructor options when instancing the `WebsocketClient`. To connect to both linear and inverse websockets, make two instances of the WebsocketClient.

---

## 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.

```javascript
Expand All @@ -207,14 +231,13 @@ const { WebsocketClient, DefaultLogger } = require('gateio-api');
// Disable all logging on the silly level
DefaultLogger.silly = () => {};

const ws = new WebsocketClient(
{ key: 'xxx', secret: 'yyy' },
DefaultLogger
);
const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger);
```

## Browser Usage

Build a bundle using webpack:

- `npm install`
- `npm build`
- `npm pack`
Expand All @@ -224,17 +247,15 @@ The bundle can be found in `dist/`. Altough usage should be largely consistent,
---

## Contributions & Thanks
### Donations
#### tiagosiebler
Support my efforts to make algo trading accessible to all - register with my referral links:
- [Bybit](https://www.bybit.com/en-US/register?affiliate_id=9410&language=en-US&group_id=0&group_type=1)
- [Binance](https://www.binance.com/en/register?ref=20983262)
- [OKX](https://www.okx.com/join/18504944)
- [FTX](https://ftx.com/referrals#a=ftxapigithub)

Or buy me a coffee using any of these:
- BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk`
- ETH (ERC20): `0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da`

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` <!-- metamask -->

### Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
25 changes: 25 additions & 0 deletions examples/futures/getBalances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { RestClient } from '../../src';

const account = {
key: process.env.API_KEY || 'yourApiHere',
secret: process.env.API_SECRET || 'yourSecretHere',
};

const gateRestClient = new RestClient({
apiKey: account.key,
apiSecret: account.secret,
});

async function getFuturesBalances() {
try {
console.log('Using API keys:', account);

// GET specific ticker
const ticker = await gateRestClient.getFuturesAccount({ settle: 'usdt' });
console.log('Response: ', ticker);
} catch (e) {
console.error(`Error in execution: `, e);
}
}

getFuturesBalances();
35 changes: 35 additions & 0 deletions examples/futures/getOrders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { RestClient } from '../../src';

const account = {
key: process.env.API_KEY || 'yourApiHere',
secret: process.env.API_SECRET || 'yourSecretHere',
};

const gateRestClient = new RestClient({
apiKey: account.key,
apiSecret: account.secret,
});

async function getFuturesOrders() {
try {
console.log('Using API keys:', account);

// get open orders
const orders = await gateRestClient.getFuturesOrders({
settle: 'usdt',
status: 'open',
});
console.log('Response: ', orders);

// get finished orders
const orders1 = await gateRestClient.getFuturesOrders({
settle: 'usdt',
status: 'finished',
});
console.log('Response: ', orders1);
} catch (e) {
console.error(`Error in execution: `, e);
}
}

getFuturesOrders();
Loading