n9sdk
v0.1.3
Published
N9 OpenAPI SDK for Node.js (REST)
Maintainers
Readme
n9sdk
N9 OpenAPI SDK for Node.js. Implements signing per docs and common REST endpoints.
N9 OpenAPI 的 Node.js SDK。按照官方文档实现签名与常用 REST 接口。
Install | 安装
npm i n9sdkUsage | 使用
Basic usage examples for initialization, market data, and trading.
下面展示初始化、行情与交易的基础用法示例。
import { N9SDKClient } from 'n9sdk';
const client = new N9SDKClient({
baseURL: 'https://openapi.n9ex.org',
apiKey: process.env.N9_API_KEY!,
apiSecret: process.env.N9_API_SECRET!,
// optional
defaultRecvWindow: 5000,
useServerTime: true,
timeoutMs: 30000,
wsURL: 'wss://ws.n9ex.org/kline-api/ws', // official WS endpoint
});
// Public market data
const ticker = await client.getTicker({ symbol: 'LTCUSDT' });
console.log(ticker);
// Create order (SIGNED)
const order = await client.newOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
volume: '1',
price: '9300',
});
// Get order (SIGNED)
const got = await client.getOrder({ symbol: 'BTCUSDT', orderId: '10001' });Notes | 注意
Signs requests with HMAC SHA256 per
X-CH-TS,X-CH-APIKEY,X-CH-SIGN.recvWindowdefaults to 5000ms per docs.Data is returned in reverse order (newest first).
根据文档,已签名请求通过
X-CH-TS、X-CH-APIKEY、X-CH-SIGN发送。recvWindow默认 5000ms,可在 SDK 中配置或按调用覆盖。接口返回数据默认是逆序(新在前)。
Reference | 参考
- Open API Doc: English
Official Endpoints | 官方端点
- REST baseURL:
https://openapi.n9ex.org - WebSocket URL:
wss://ws.n9ex.org/kline-api/ws
Implemented Endpoints | 已实现端点
- Spot (MARKET_DATA):
/sapi/v1/ticker,/sapi/v1/depth,/sapi/v1/trades,/sapi/v1/klines,/sapi/v1/exchangeInfo,/sapi/v1/time - Spot (SIGNED):
/sapi/v1/order(POST/GET),/sapi/v1/order/cancel(POST),/sapi/v1/openOrders,/sapi/v1/allOrders,/sapi/v1/account,/sapi/v1/myTrades - Margin (SIGNED):
/sapi/v1/margin/account,/sapi/v1/margin/transfer,/sapi/v1/margin/loan,/sapi/v1/margin/repay,/sapi/v1/margin/order(POST/GET/cancel),/sapi/v1/margin/openOrders,/sapi/v1/margin/allOrders,/sapi/v1/margin/myTrades - Capital (SIGNED):
/sapi/v1/capital/withdraw/apply,/sapi/v1/capital/deposit/address,/sapi/v1/capital/withdraw/history,/sapi/v1/capital/deposit/history - Contract (MIX):
/fapi/v1/exchangeInfo,/fapi/v1/ticker/price,/fapi/v1/order(POST/GET/cancel),/fapi/v1/account,/fapi/v1/positionRisk,/fapi/v1/fundingRate - User Stream:
/sapi/v1/userDataStreamcreate/keepalive/close
Configuration & Auth | 配置与认证
Set baseURL, API credentials, and optional recvWindow/server time sync.
配置 baseURL、API 密钥;可选设置 recvWindow 与服务端时间同步。
const client = new N9SDKClient({
baseURL: 'https://openapi.n9ex.org',
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_SECRET',
defaultRecvWindow: 5000, // default per docs
useServerTime: true, // auto sync server time
});
// Manually sync server time if needed
await client.syncServerTime();Spot (Market Data) | 现货(行情)
Public, no signature required.
公开接口,无需签名。
// Ticker
await client.getTicker({ symbol: 'BTCUSDT' });
// Order Book Depth
await client.getDepth({ symbol: 'BTCUSDT', limit: 50 });
// Recent Trades
await client.getTrades({ symbol: 'BTCUSDT', limit: 100 });
// Klines
await client.getKlines({ symbol: 'BTCUSDT', interval: '1m', limit: 500 });
// Exchange Info
await client.getExchangeInfo();
// Server Time
await client.syncServerTime();Spot (Trade / User Data) | 现货(交易 / 用户数据)
Signed endpoints require API key, secret, timestamp and signature.
已签名端点需要 API Key、Secret、时间戳与签名。
// New Order (MARKET)
await client.newOrder({ symbol: 'BTCUSDT', side: 'BUY', type: 'MARKET', volume: '1' });
// New Order (LIMIT)
await client.newOrder({ symbol: 'BTCUSDT', side: 'SELL', type: 'LIMIT', volume: '0.5', price: '9500' });
// Query Order
await client.getOrder({ symbol: 'BTCUSDT', orderId: '123456' });
// Cancel Order
await client.cancelOrder({ symbol: 'BTCUSDT', orderId: '123456' });
// Open Orders
await client.getOpenOrders({ symbol: 'BTCUSDT' });
// All Orders (history)
await client.getAllOrders({ symbol: 'BTCUSDT', limit: 100 });
// Account Info
await client.getAccountInfo();
// My Trades
await client.getMyTrades({ symbol: 'BTCUSDT', limit: 100 });Margin | 杠杆
Margin account, transfers, borrow/repay, and orders.
包含杠杆账户、资金划转、借贷/还款与下单等。
// Margin Account
await client.getMarginAccount();
// Transfer (Spot <-> Margin)
await client.marginTransfer({ asset: 'USDT', amount: '100', type: 1 });
// Loan
await client.marginLoan({ asset: 'USDT', amount: '50' });
// Repay
await client.marginRepay({ asset: 'USDT', amount: '50' });
// Place Margin Order
await client.newMarginOrder({ symbol: 'BTCUSDT', side: 'BUY', type: 'MARKET', volume: '0.01' });
// Query Margin Order
await client.getMarginOrder({ symbol: 'BTCUSDT', orderId: '789' });
// Cancel Margin Order
await client.cancelMarginOrder({ symbol: 'BTCUSDT', orderId: '789' });
// Open Margin Orders
await client.getMarginOpenOrders({ symbol: 'BTCUSDT' });
// All Margin Orders
await client.getMarginAllOrders({ symbol: 'BTCUSDT', limit: 100 });
// My Margin Trades
await client.getMarginMyTrades({ symbol: 'BTCUSDT', limit: 100 });Capital (Withdraw / Deposit) | 资金(提现 / 充值)
Withdraw apply, deposit address, histories.
提现申请、充值地址与历史记录。
// Apply Withdraw
await client.withdrawApply({ coin: 'USDT', address: 'YOUR_ADDRESS', amount: '10', network: 'TRX' });
// Deposit Address
await client.getDepositAddress({ coin: 'USDT', network: 'TRX' });
// Withdraw History
await client.getWithdrawHistory({ coin: 'USDT', limit: 100 });
// Deposit History
await client.getDepositHistory({ coin: 'USDT', limit: 100 });Contract | 合约
Futures/Perpetual endpoints (paths may vary by deployment).
合约/永续相关接口(路径可能因不同部署略有差异)。
// Exchange Info
await client.contractExchangeInfo();
// Ticker Price
await client.contractTicker({ symbol: 'BTCUSDT' });
// New Contract Order
await client.newContractOrder({ symbol: 'BTCUSDT', side: 'BUY', type: 'LIMIT', quantity: '0.01', price: '30000' });
// Query Contract Order
await client.getContractOrder({ symbol: 'BTCUSDT', orderId: '345' });
// Cancel Contract Order
await client.cancelContractOrder({ symbol: 'BTCUSDT', orderId: '345' });
// Account
await client.getContractAccount();
// Positions
await client.getContractPositions();
// Funding Rate
await client.getFundingRate({ symbol: 'BTCUSDT', limit: 100 });User Stream (REST) | 用户数据流(REST)
// Create listen key (API key only)
const { listenKey } = await client.createListenKey();
// Keepalive (call periodically)
await client.keepAliveListenKey(listenKey);
// Close when done
await client.closeListenKey(listenKey);WebSocket | WebSocket
The SDK exposes a lightweight WS client. Provide your WS URL from the exchange.
SDK 提供轻量级 WS 客户端;请填写交易所提供的 WS 地址。
import { N9WebSocketClient } from 'n9sdk';
const wsUrl = 'wss://ws.n9ex.org/kline-api/ws';
const ws = new N9WebSocketClient({ url: wsUrl });
ws.connect(
(msg) => {
console.log('WS message:', msg);
},
() => console.log('WS open'),
(code, reason) => console.log('WS closed', code, reason),
(err) => console.error('WS error', err)
);
// ws.send({ op: 'subscribe', args: [...] }); // if your WS requires a subscribe message
// ws.close();WebSocket Commands | WebSocket 命令封装
The SDK wraps common commands per docs and auto-decompresses gzip binary frames, and replies pong for { "ping": <ts> }.
SDK 已封装常用命令(与文档一致),自动解压 gzip(二进制)消息,并对 { "ping": <ts> } 自动回复 pong。
// Subscribe (sub)
ws.subscribeDepth('btcusdt');
ws.subscribeTrade('btcusdt');
ws.subscribeTicker('btcusdt');
ws.subscribeKline('btcusdt', '1min'); // intervals: 1min/5min/15min/30min/60min/1day/1week/1month
// Unsubscribe (unsub)
ws.unsubscribeDepth('btcusdt');
ws.unsubscribeTrade('btcusdt');
ws.unsubscribeTicker('btcusdt');
ws.unsubscribeKline('btcusdt', '1min');
// Request history (req)
ws.requestKlineHistory('btcusdt', '5min', { endIdx: 1506602880, pageSize: 100 });
ws.requestHistoryTrade('btcusdt');For channel formats and payload examples, see the docs: WebSocket English
关于频道格式与返回样例,请参考文档:WebSocket 英文
Error Handling | 错误处理
try {
const res = await client.getTicker({ symbol: 'BTCUSDT' });
console.log(res);
} catch (e: any) {
// Non-2xx throws N9ApiError with status and payload (may include { code, msg })
if (e.name === 'N9ApiError') {
console.error('status:', e.status);
console.error('payload:', e.payload); // e.payload?.code, e.payload?.msg
}
console.error('Request failed:', e.message);
}错误处理要点:
- 若服务端返回
{ code, msg }(如文档所示),SDK 会将其放在e.payload中;HTTP 状态码在e.status。 - 请根据文档的错误码表进行业务级处理。
Enums | 枚举
import { Enums } from 'n9sdk';
const side: Enums.Side = Enums.Side.BUY;
const orderType: Enums.SpotOrderType = Enums.SpotOrderType.LIMIT;IDE Hints for Params | 参数提示(IDE)
All request params are strongly typed and documented with bilingual JSDoc. Your IDE will show hints in English and Chinese.
所有请求参数均提供了强类型与中英双语 JSDoc 注释,IDE 将自动显示提示。
import type { NewOrderParams, NewContractOrderParams } from 'n9sdk';
const spotOrder: NewOrderParams = {
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
volume: '1',
price: '9300',
};
await client.newOrder(spotOrder);
const contractOrder: NewContractOrderParams = {
symbol: 'E-BTC-USDT',
side: 'BUY',
type: 'LIMIT',
quantity: '1',
price: '30000',
};
await client.newContractOrder(contractOrder);常用枚举:
Side: 买/卖(BUY/SELL)SpotOrderType: 现货下单类型(MARKET/LIMIT)Interval: K 线周期(如 1m/1h/1d 等)
