kucoin-spot-api
v1.0.14
Published
Extended KuCoin Nodejs Spot API Wrapper
Downloads
76
Maintainers
Readme
kucoin-spot-api
This is an open source project created to utilize the Kucoin v2 API to support automated, algorithmic trading. The project was made and tested for Node 8.0+.
There are no guarentees towards the stability or effectiveness of this project. Comments, contributions, stars and donations are, however, all welcome.
Installation
npm install kucoin-spot-api
Alternatively, you can clone/download the repository and import into your project by file path.
Getting Started
To begin using the API wrapper, require it, create a config object that contains all your necessay information provided by Kucoin. Then run the custom init() function with your config object as a parameter. If you are only using Public endpoints, the config object only requires the environment key/value pair.
- Define "apiKeyVersion" according to your api key version (v2, v3, ...etc)
- Define "environment" as "sandbox" if you want to test your code (baseTestUrl will be used according to the baseTestUrlIndex)
- Define "baseUrlIndex" according to KuCoin's REST API base url address (if environment not defined as "sandbox" this key will be effective)
- Define "baseTestUrlIndex" according to KuCoin's REST API base test url address (if environment defined as "sandbox" this key will be effective)
API updated according to the KuCoin's current endpoints (05.08.2024):
- https://www.kucoin.com/docs/rest/spot-trading/market-data/get-currency-list
Updated methods:
- api.listFills({..., tradeType: 'TRADE'}): tradeType parameter is mandatory!
Be careful about using this API. There is a request rate limit that defined by your VIP level. Request rate of your code MUST be under KuCoin's request limits. For more information:
- https://www.kucoin.com/docs/basic-info/request-rate-limit/rest-api
- https://www.kucoin.com/docs/basic-info/request-rate-limit/websocket
Example code is as follows:
const api = require('kucoin-spot-api')
const config = {
baseUrlIndex: 0,
baseTestUrlIndex: 0,
environment: 'live',
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxx',
apiKeyVersion: '3',
secretKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
passphrase: 'xxxxxx',
}
api.init(config)
Using the API Wrapper
Once the API wrapper object is created, you can call any of the associated functions. They will return a Promise which can be utlized with .then/.catch or async/await. Note that the Promise based approach will return directly whereas the async/await approach requires calling the function.
Simple example:
// Promise based approach for getting account information (private & signed)
api.getAccounts().then((r) => {
console.log(r.data)
}).catch((e) => {
console.log(e))
})
// Async/Await get account info example (private & signed)
async function getAccounts() {
try {
let r = await api.getAccounts()
console.log(r.data)
} catch(err) {
console.log(err)
}
}
This approach allows for more complex multi-call asynchronous functionality, especially useful for automated trading.
Market Endpoint (Public)
Public endpoints do not require an API Key, Secret Key or API Passphrase.
/*
Get Symbols List
GET /api/v2/symbols
market = string [optional]
*/
api.getSymbols(market)
/*
Get Ticker
GET /api/v1/market/orderbook/level1?symbol=<symbol>
symbol = string
*/
api.getTicker(symbol)
/*
Get All Tickers
GET /api/v1/market/allTickers
*/
api.getAllTickers()
/*
Get 24hr Stats
GET /api/v1/market/stats?symbol=<symbol>
symbol = string
*/
api.get24hrStats(symbol)
/*
Get Market List
GET /api/v1/markets
*/
api.getMarketList()
/*
Get Part Order Book (aggregated)
GET /api/v1/market/orderbook/level2_20?symbol=<symbol>
GET /api/v1/market/orderbook/level2_100?symbol=<symbol>
params = {
amount: integer (20 || 100)
symbol: string
}
*/
api.getPartOrderBook(params)
/*
Get Full Order Book (aggregated)
GET /api/v3/market/orderbook/level2?symbol=<symbol>
symbol = string
*/
api.getOrderBook(symbol)
/*
Get Full Order Book (aggregated)
GET /api/v3/market/orderbook/level2?symbol=<symbol>
symbol = string
*/
api.getFullOrderBook(symbol)
/*
Get Full Order Book (atomic)
GET /api/v1/market/orderbook/level3?symbol=<symbol>
symbol = string
*/
api.getFullOrderBookAtomic(symbol)
/*
Get Trade Histories
GET /api/v1/market/histories?symbol=<symbol>
symbol = string
*/
api.getTradeHistories(symbol)
/*
Get Klines
GET /api/v1/market/candles?symbol=<symbol>
params = {
symbol: string
startAt: long (unix time)
endAt: long (unix time)
type: enum [1min, 3min, 5min, 15min, 30min, 1hour, 2hour, 4hour, 6hour, 8hour, 12hour 1day, 1week]
}
*/
api.getKlines(params)
/*
Get currencies
GET /api/v3/currencies
*/
api.getCurrencies()
/*
Get currency detail
GET /api/v3/currencies/{currency}
currency = string
*/
api.getCurrency(currency)
/*
Get Fiat Price
GET /api/v1/prices
params = {
base: string (e.g. 'USD') [optional]
currencies: array
}
*/
api.getFiatPrices(params)
/*
Server Time
GET /api/v1/timestamp
*/
api.getServerTime()
/*
Service Status
GET /api/v1/status
*/
api.getServiceStatus()
User Endpoints (Private)
/*
User Info
GET /api/v2/user-info
*/
api.getUserInfo()
/*
List Accounts
GET /api/v1/accounts
params = {
currency: string [optional]
type: string [optional]
}
*/
api.getAccounts(params)
/*
Get Account
GET /api/v1/accounts/<account-id>
params {
id: account-id
}
*/
api.getAccountById(params)
/*
Create Account
POST /api/v1/accounts
params = {
type: string ['main' || 'trade']
currency: string
}
*/
api.createAccount(params)
/*
Get Account Ledgers
GET /api/v1/accounts/<accountId>/ledgers
params = {
id: string
startAt: long (unix time)
endAt: long (unix time)
}
*/
api.getAccountLedgers(params)
/*
Get Holds
GET /api/v1/accounts/<accountId>/holds
params = {
id: string
}
*/
api.getHolds(params)
/*
Inner Transfer
POST /api/accounts/inner-transfer
params = {
clientOid: string
currency: string,
from: string
to: string
amount: string
}
*/
api.innerTransfer(params)
/*
Create Deposit Address
POST /api/v1/deposit-addresses
params = {
currency: string
}
*/
api.createDepositAddress(params)
/*
Get Deposit Address
GET /api/v1/deposit-addresses?currency=<currency>
params = {
currency: string
}
*/
api.getDepositAddress(params)
/*
Get Repay Record
GET /api/v1/margin/borrow/outstanding
params = {
currency: string [optional]
currentPage: string [optional (default 1)]
pageSize: string [optional (default 50)]
}
*/
api.getRepayRecord(params)
/*
Get Deposit List
GET /api/v1/deposits
params = {
currency: string [optional]
startAt: long (unix time)
endAt: long (unix time)
status: string [optional]
}
*/
api.getDepositList(params)
/*
Get Margin Account
GET /api/v1/margin/account
*/
api.getMarginAccount()
/*
Get Withdrawals List
GET /api/v1/withdrawals
params = {
currency: string [optional]
startAt: long (unix time)
endAt: long (unix time)
status: string [optional]
}
*/
api.getWithdrawalsList(params)
/*
Get Repay Record
GET /api/v1/margin/borrow/outstanding
params = {
currency: string [optional]
currentPage: string [optional (default 1)]
pageSize: string [optional (default 50)]
}
*/
api.getRepayRecord(params)
/*
Get Withdrawal Quotas
GET /api/v1/withdrawals/quotas
params = {
currency: string
}
*/
api.getWithdrawalQuotas(params)
/*
Apply Withdrawal
POST /api/v1/withdrawals
params = {
currency: string
address: string
amount: number
memo: string [optional]
isInner: boolean [optional]
remark: string [optional]
}
*/
api.applyForWithdrawal(params)
/*
Cancel Withdrawal
DELETE /api/v1/withdrawls/<withdrawlId>
params = {
withdrawalId: string
}
*/
api.cancelWithdrawal(params)
/*
Get V1 Historical Withdrawals List
GET /api/v1/hist-withdrawals
params = {
currentPage: integer [optional]
pageSize: integer [optional]
currency: string [optional - currency code]
startAt: long (unix time) [optional]
endAt: long (unix time) [optional]
status: string [optional] Available value: PROCESSING, SUCCESS, and FAILURE
}
*/
api.getV1HistoricalWithdrawls(params)
/*
Get V1 Historical Deposits List
GET /api/v1/hist-deposits
params = {
currentPage: integer [optional]
pageSize: integer [optional]
currency: string [optional - currency code]
startAt: long (unix time) [optional]
endAt: long (unix time) [optional]
status: string [optional] Available value: PROCESSING, SUCCESS, and FAILURE
}
*/
api.getV1HistoricalDeposits(params)
Trade Endpoints (Private)
/*
Place a new order
POST /api/v1/orders
Details for market order vs. limit order and params see https://docs.kucoin.com/#place-a-new-order
General params
params = {
clientOid: string
side: string ['buy' || 'sell']
symbol: string
type: string [optional, default: limit]
remark: string [optional]
stop: string [optional] - either loss or entry and needs stopPrice
stopPrice: string [optional] - needed for stop
stp: string [optional] (self trade prevention)
price: string,
size: string,
timeInForce: string [optional, default is GTC]
cancelAfter: long (unix time) [optional]
hidden: boolean [optional]
iceberge: boolean [optional]
iceberg: boolean [optional]
visibleSize: string [optional]
}
*/
api.placeOrder(params)
/*
Place a new order
POST /api/v1/orders/multi
params = [{
clientOid: string
side: string ['buy' || 'sell']
symbol: string
type: string [optional, default: limit]
remark: string [optional]
stop: string [optional] - either loss or entry and needs stopPrice
stopPrice: string [optional] - needed for stop
stp: string [optional] (self trade prevention)
price: string,
size: string,
timeInForce: string [optional, default is GTC]
cancelAfter: long (unix time) [optional]
hidden: boolean [optional]
iceberge: boolean [optional]
iceberg: boolean [optional]
visibleSize: string [optional]
}, {...}, ..., {}
]
*/
api.placeMultipleOrder(params)
/*
Cancel an order
DELETE /api/v1/orders/<order-id>
params = {
id: order-id
}
*/
api.cancelOrder(params)
/*
Cancel an order by clientOid
DELETE /api/v1/orders/client-order/<clientOid>
params = {
id: clientOid
}
*/
api.cancelOrderByClientOid(params)
/*
Cancel all orders
DELETE /api/v1/orders
params = {
symbol: string [optional]
tradeType: string [optional, TRADE: Spot Trading(default), MARGIN_TRADE: Cross Margin Trading, MARGIN_ISOLATED_TRADE: Isolated Margin Trading]
}
*/
api.cancelAllOrders(params)
/*
List orders
GET /api/v1/orders
params = {
status: string [optional, default: dealt, alt: active]
symbol: string [optional]
side: string [optional, 'buy' || 'sell']
type: string [optional, limit || limit_stop || market_stop]
startAt: long (unix time) [optional]
endAt: long (unix time) [optional]
tradeType: string [optional, TRADE: Spot Trading(default), MARGIN_TRADE: Cross Margin Trading, MARGIN_ISOLATED_TRADE: Isolated Margin Trading]
}
*/
api.getOrders(params)
/*
Get recent orders
GET /api/v1/limit/orders
*/
api.getRecentOrders()
/*
Get an order
GET /api/v1/orders/<order-id>
params = {
id: order-id
}
*/
api.getOrderById(params)
/*
Get an order by clientOid
GET /api/v1/order/client-order/<clientOid>
params = {
id: clientOid
}
*/
api.getOrderByClientOId(params)
/*
List Fills
GET /api/v1/fills
params: {
orderId: string [optional]
symbol: string [optional]
side: string [optional, 'buy' || 'sell']
type: string [optional]
startAt: long (unix time) [optional]
endAt: long (unix time) [optional]
tradeType: string [mandatory, TRADE: Spot Trading(default), MARGIN_TRADE: Cross Margin Trading, MARGIN_ISOLATED_TRADE: Isolated Margin Trading]
}
*/
api.listFills(params)
/*
List Your Recent Fills: max 1000 fills in the last 24 hours, all symbols
GET /api/v1/limit/fills
*/
api.recentFills()
/*
Get V1 Historical Orders List
GET /api/v1/hist-orders
params: {
currentPage: integer [optional]
pageSize: integer [optional]
symbol: string [optional]
startAt: long (unix time) [optional]
endAt: long (unix time) [optional]
side: string (buy || sell) [optional]
}
*/
api.getV1HistoricalOrders(params)
Websockets
The websocket component of the API wrapper is utilized by initializing websockets based on topics that match Kucoin endpoints. These include:
- 'ping'
- 'ticker'
- 'allTicker'
- 'symbolSnapshot'
- 'marketSnapshot'
- 'orderbook'
- 'match'
- 'fullMatch' (optional - private)
- 'orders' (private)
- 'balances' (private)
To initialize a websocket, provide the paramaters and an event handler. A simple example is as follows:
// Parameters
params = {
topic: enum (see above)
symbols: array (ignored if not required by the endpoint, single array element if single, multiple if desired)
}
// Public streaming websocket for the orderbook of the provide symbol(s)
api.initSocket({topic: "orderbook", symbols: ['KCS-BTC']}, (msg) => {
let data = JSON.parse(msg)
console.log(data)
})
// Private streaming websocket for account balances
api.initSocket({topic: "balances"}, (msg) => {
let data = JSON.parse(msg)
console.log(data)
})
The event handler can be programmed to manipulate/store the returned websocket stream data as desired.
Donation Addresses
BTC: 36yHzdX4XFXh7EQVJpUbJhxP8svS1oY18N (BTC)
ETH: 0x5112f2e20bc3c97426c7ea9ee3e40e5edf9d3e64 (ERC20)
USDT: TVRzZDTemdTA4hydAticBQbuq9C4CNdv1Z (TRC20)
License
This project is open source and uses the ISC license. Feel free to utilize it in whatever way you see fit.