unified-exchanges-api-node
v1.1.6
Published
Unified Crypto Exchanges API for Node.js
Readme
Unified Exchanges API for Node.js
A powerful, unified interface for interacting with major cryptocurrency exchanges (Binance, Bybit, OKX). This package simplifies the process of connecting to exchanges, fetching market data, managing real-time streams, and executing orders across Futures markets.
Table of Contents
Installation
npm install unified-exchanges-api-nodeGetting Started
The entry point for using this package is the ExchangeFactory. It allows you to create a unified connection to a specific exchange.
import { ExchangeFactory, BinanceUserData } from 'unified-exchanges-api-node';
// Initialize connection (API Key & Secret are optional for public data)
const binance = ExchangeFactory.create('binance', 'YOUR_API_KEY', 'YOUR_API_SECRET');
// Access Spot, Futures, or Streams
async function main() {
// Example: Get Futures Depth Snapshot
const depth = await binance.futures.getStaticDepth({ symbol: 'BTCUSDT'});
console.log(depth);
// Example: Connect to Futures Depth Stream
await binance.streams.futuresDepthStream(['BTCUSDT'], (data) => {
console.log('Depth Update:', data);
});
// Example: Subscribe to User Data Events (if keys provided)
if (binance.userData) {
await binance.userData.init();
// Subscribe to position updates
const offSubscribe = binance.userData.onPositionUpdate(positionUpdate => {
console.log(positionUpdate)
})
// Call offSubscribe to remove subscription
// offSubscribe();
}
}
main();WebSocket order entry (Binance, Bybit, and OKX Futures)
Pass useWebsocketApi: true in the connection options to send supported futures
order operations over the exchange's authenticated WebSocket API:
import { ExchangeFactory, ExchangeList } from 'unified-exchanges-api-node';
const bybit = ExchangeFactory.create(
ExchangeList.BYBIT,
'YOUR_API_KEY',
'YOUR_API_SECRET',
undefined,
false,
{ useWebsocketApi: true }
);
const order = await bybit.futures.marketBuy({
symbol: 'BTCUSDT',
quantity: 0.001
});Bybit uses WebSocket order entry for order creation and single-order cancellation.
If the WebSocket is unavailable, those calls fall back to signed REST. Bybit does
not provide a WebSocket cancel-all operation, so cancelAllOpenOrders continues
to use REST.
OKX uses WebSocket order entry for regular order creation and single-order
cancellation. Algo orders such as triggers and trailing stops, along with the
library's multi-type cancelAllOpenOrders workflow, continue to use REST.
Architecture Overview
When you create a connection using ExchangeFactory, it returns an IUnifiedExchange object containing:
- spot: An
IExchangeClientinstance for Spot market operations. - futures: An
IExchangeClientinstance for Futures market operations. - streams: An
IStreamManagerinstance for handling WebSocket streams. - userData (Optional): An
IUserDataManagerinstance for managing account state (orders, positions) via WebSockets and REST synchronization.
API Documentation
ExchangeFactory
Static class to instantiate exchange connections.
create(exchangeId: string, apiKey?: string, apiSecret?: string): IUnifiedExchange
Creates a new unified exchange instance.
| Parameter | Type | Description |
| :---------- | :------- | :----------------------------------------------- |
| exchangeId| string | The exchange identifier (e.g., 'binance', 'bybit'). |
| apiKey | string | (Optional) Your API Key. |
| apiSecret | string | (Optional) Your API Secret. |
Returns: IUnifiedExchange
Spot & Futures Client (IUnifiedExchange.spot / .futures)
Both properties implement the IExchangeClient interface.
Note: Authorized (trading) methods are NOT implemented for the
spotclient. They are only available forfutures.
Connection Management
closeListenKey(): Close the user data stream listen key.
Market Data (Public)
getExchangeInfo(): Returns unified exchange info with symbol details.getStaticDepth(params): Fetch order book snapshot.getKlines(params): Fetch historical candlestick data.getAggTrades(params): Fetch recent aggregate trades.getLatestPnlBySymbol(symbol): Get PnL for a specific symbol.
Account Data (Authorized)
getBalance(): Get account wallet balance.getPositionRisk(): Get position risk information.getOpenPositions(): Get all open positions.getOpenPositionBySymbol(params): Get open position for a specific symbol.
Order Management (Authorized - Futures Only)
getOpenOrders(): Fetch all active orders.getOpenOrdersBySymbol(params): Fetch active orders for a symbol.cancelAllOpenOrders(params): Cancel all orders for a symbol.cancelOrderById(params): Cancel a specific order by ID.
Order Execution (Authorized - Futures Only)
marketBuy(params)/marketSell(params): Execute Market orders.limitBuy(params)/limitSell(params): Execute Limit orders.stopOrder(params): Execute Stop Loss orders.stopMarketOrder(params): Execute Stop Market orders.trailingStopOrder(params): Execute Trailing Stop orders.reduceLimitOrder(params): Place a reduce-only limit order.reducePosition(params): Close/Reduce a position.customOrder(orderInput): Send a custom order payload.
Stream Manager (IUnifiedExchange.streams)
Implements IStreamManager. Handles real-time WebSocket connections.
Lifecycle
closeAllSockets(): Closes all active WebSocket connections.closeById(id): Closes a specific socket by its ID.
Spot WebSockets
spotDepthStream(symbols, callback): Subscribe to order book depth updates.spotCandleStickStream(symbols, interval, callback): Subscribe to candlestick/kline updates.spotBookTickerStream(symbols, callback): Subscribe to best bid/ask (book ticker) updates.spotTradeStream(symbols, callback): Subscribe to real-time trade execution updates.
Futures WebSockets
futuresDepthStream(symbols, callback): Subscribe to order book depth updates (Futures).futuresCandleStickStream(symbols, interval, callback): Subscribe to candlestick/kline updates (Futures).futuresBookTickerStream(symbols, callback): Subscribe to best bid/ask (book ticker) updates (Futures).futuresTradeStream(symbols, callback): Subscribe to real-time trade execution updates (Futures).fundingStream(symbols, callback, statusCallback?, options?): Subscribe to funding rate updates. Setoptions.fetchIntervalto enrich exchanges whose stream does not include the funding interval. The interval is expressed in hours, initialized on the first event, and refreshed at most once per symbol during minute00UTC.futuresUserDataStream(callback): Subscribe to private account updates (order status, balance updates, etc.).
User Data Manager (IUnifiedExchange.userData)
Implements IUserDataManager. Available only if API keys are provided.
The UserData manager acts as a Single Source of Truth for your account state. It initializes by fetching a REST snapshot of your Orders and Positions, and then maintains this state in real-time via a private WebSocket stream.
Usage (Event Subscription)
To listen for real-time updates (like order fills or position changes), you must subscribe to the Static Events of the specific exchange class (BinanceUserData or BybitUserData).
Example:
import { ExchangeFactory, BinanceUserData, BybitUserData } from 'unified-exchanges-api-node';
const binance = ExchangeFactory.create('binance', 'KEY', 'SECRET');
if (binance.userData) {
// 1. Initialize (Start Stream)
await binance.userData.init();
// 2. Subscribe to Static Events
BinanceUserData.Emitter.on(BinanceUserData.POSITION_EVENT, (symbol, position) => {
console.log(`[Binance] Position updated for ${symbol}`, position);
});
BinanceUserData.Emitter.on(BinanceUserData.ORDER_EVENT, (symbol, orders) => {
console.log(`[Binance] Order list updated for ${symbol}`, orders);
});
}Event Reference
All UserData classes (BinanceUserData, BybitUserData) export the following static event constants:
| Event Constant | Description | Payload Arguments |
| :--- | :--- | :--- |
| POSITION_EVENT | Emitted when a position is updated. | (symbol: string, position: PositionData) |
| ORDER_EVENT | Emitted when the order list changes. | (symbol: string, orders: OrderData[]) |
| TRIGGER_POSITION_EVENT | Emit this to request current position. | (symbol: string) |
| TRIGGER_ORDER_EVENT | Emit this to request current orders. | (symbol: string) |
Manual Trigger Example:
If you need to get the current state for a symbol on-demand via the event system:
// Request state check
BinanceUserData.Emitter.emit(BinanceUserData.TRIGGER_POSITION_EVENT, 'BTCUSDT');
// ... The 'POSITION_EVENT' will be emitted immediately with the cached data.Class Properties & Methods
userData: Holds the current synchronous state:positions: Array ofPositionData.orders: Array ofOrderData.
init(): Connects the WebSocket and fetches initial snapshots.requestAllOrders(): Force-refresh all open orders from API.requestAllPositions(): Force-refresh all open positions from API.
