binance-futures-wrapper
Version:
A comprehensive TypeScript wrapper for Binance USDT-M Futures API with full REST and WebSocket support
342 lines • 10.2 kB
JavaScript
"use strict";
/**
* Main Binance Futures Client
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinanceFuturesClient = void 0;
const events_1 = require("events");
const rest_1 = require("./rest");
const websocket_1 = require("./websocket");
const utils_1 = require("./utils");
class BinanceFuturesClient extends events_1.EventEmitter {
constructor(config) {
super();
this.listenKey = null;
this.keepAliveInterval = null;
(0, utils_1.validateConfig)(config);
this.config = {
recvWindow: 5000,
enableLogging: false,
testnet: false,
autoConnectUserStream: false,
...config
};
this.logger = new utils_1.Logger(this.config.enableLogging, '[BinanceFuturesClient]');
// Initialize REST client
this.rest = new rest_1.RestClient(this.config);
// Initialize WebSocket client
this.ws = new websocket_1.WebSocketClient({
config: this.config,
...this.config.wsConfig
});
this.setupEventHandlers();
this.logger.log('Binance Futures Client initialized', {
testnet: this.config.testnet,
autoConnectUserStream: this.config.autoConnectUserStream
});
}
setupEventHandlers() {
// Forward WebSocket events
this.ws.on('marketConnected', () => {
this.logger.log('Market WebSocket connected');
this.emit('marketConnected');
});
this.ws.on('marketDisconnected', (data) => {
this.logger.warn('Market WebSocket disconnected', data);
this.emit('marketDisconnected', data);
});
this.ws.on('userConnected', () => {
this.logger.log('User WebSocket connected');
this.emit('userConnected');
});
this.ws.on('userDisconnected', (data) => {
this.logger.warn('User WebSocket disconnected', data);
this.emit('userDisconnected', data);
});
this.ws.on('marketData', (data) => {
this.emit('marketData', data);
});
// Forward processed market data events with type safety
this.ws.on('marketDataProcessed', (data) => {
this.emit('marketDataProcessed', data);
});
this.ws.on('userData', (data) => {
this.emit('userData', data);
});
// Forward processed user data events with type safety
this.ws.on('userDataProcessed', (data) => {
this.emit('userDataProcessed', data);
// Emit specific typed events for common use cases
if (data.eventType === 'ORDER_TRADE_UPDATE') {
this.emit('orderUpdate', data);
}
else if (data.eventType === 'ACCOUNT_UPDATE') {
this.emit('accountUpdate', data);
}
});
this.ws.on('keepAliveRequest', async () => {
if (this.listenKey) {
try {
await this.rest.keepaliveListenKey({ listenKey: this.listenKey });
this.logger.debug('Listen key kept alive');
}
catch (error) {
this.logger.error('Failed to keep alive listen key:', error);
this.emit('error', error);
}
}
});
}
/**
* Initialize the client - connect WebSocket streams if configured
*/
async initialize() {
this.logger.log('Initializing client...');
if (this.config.autoConnectUserStream) {
await this.connectUserStream();
}
this.logger.log('Client initialized successfully');
}
/**
* Connect to user data stream
*/
async connectUserStream() {
if (!this.listenKey) {
const response = await this.rest.createListenKey();
this.listenKey = response.listenKey;
this.logger.log('Created listen key:', this.listenKey);
}
await this.ws.connectUser(this.listenKey);
}
/**
* Connect to market data stream
*/
async connectMarketStream() {
await this.ws.connectMarket();
}
/**
* Disconnect all streams and cleanup
*/
async disconnect() {
this.logger.log('Disconnecting client...');
if (this.keepAliveInterval) {
clearInterval(this.keepAliveInterval);
this.keepAliveInterval = null;
}
if (this.listenKey) {
try {
await this.rest.closeListenKey({ listenKey: this.listenKey });
this.logger.log('Closed listen key');
}
catch (error) {
this.logger.error('Failed to close listen key:', error);
}
this.listenKey = null;
}
this.ws.close();
this.logger.log('Client disconnected');
this.emit('disconnected');
}
/**
* Get client status
*/
getStatus() {
const wsStatus = this.ws.getStatus();
return {
connected: {
market: wsStatus.market,
user: wsStatus.user
},
subscriptions: wsStatus.subscriptions,
listenKey: this.listenKey
};
}
// Market Data Convenience Methods
/**
* Get current server time
*/
async getServerTime() {
return this.rest.time();
}
/**
* Get exchange information
*/
async getExchangeInfo() {
return this.rest.exchangeInfo();
}
/**
* Get order book
*/
async getOrderBook(symbol, limit) {
return this.rest.orderBook({ symbol, limit });
}
/**
* Get recent trades
*/
async getRecentTrades(symbol, limit) {
return this.rest.trades({ symbol, limit });
}
/**
* Get klines/candlestick data
*/
async getKlines(symbol, interval, limit, startTime, endTime) {
return this.rest.klines({ symbol, interval, limit, startTime, endTime });
}
/**
* Get 24hr ticker statistics
*/
async get24hrTicker(symbol) {
return this.rest.ticker24hr(symbol ? { symbol } : undefined);
}
/**
* Get latest price
*/
async getPrice(symbol) {
return this.rest.tickerPrice(symbol ? { symbol } : undefined);
}
/**
* Get best price/qty on order book
*/
async getBookTicker(symbol) {
return this.rest.bookTicker(symbol ? { symbol } : undefined);
}
// Account/Trading Convenience Methods
/**
* Get account information
*/
async getAccount() {
return this.rest.account();
}
/**
* Get account balance
*/
async getBalance() {
return this.rest.balance();
}
/**
* Get position information
*/
async getPositions(symbol) {
return this.rest.positionRisk(symbol ? { symbol } : undefined);
}
/**
* Place a new order
*/
async createOrder(params) {
return this.rest.newOrder(params);
}
/**
* Cancel an order
*/
async cancelOrder(params) {
return this.rest.cancelOrder(params);
}
/**
* Cancel all orders for a symbol
*/
async cancelAllOrders(symbol) {
return this.rest.cancelAllOrders({ symbol });
}
/**
* Get order status
*/
async getOrder(params) {
return this.rest.getOrder(params);
}
/**
* Get all open orders
*/
async getOpenOrders(symbol) {
return this.rest.getOpenOrders(symbol ? { symbol } : undefined);
}
/**
* Get all orders (active, canceled, filled)
*/
async getAllOrders(params) {
return this.rest.getAllOrders(params);
}
/**
* Change leverage for a symbol
*/
async changeleverage(symbol, leverage) {
return this.rest.changeInitialLeverage({ symbol, leverage });
}
/**
* Change margin type
*/
async changeMarginType(symbol, marginType) {
return this.rest.changeMarginType({ symbol, marginType });
}
// WebSocket Convenience Methods
/**
* Subscribe to aggregate trades
*/
async subscribeAggTrades(symbol) {
if (!this.ws.getStatus().market) {
await this.connectMarketStream();
}
await this.ws.subscribeAggTrade(symbol);
}
/**
* Subscribe to klines
*/
async subscribeKlines(symbol, interval) {
if (!this.ws.getStatus().market) {
await this.connectMarketStream();
}
await this.ws.subscribeKline(symbol, interval);
}
/**
* Subscribe to 24hr ticker
*/
async subscribeTicker(symbol) {
if (!this.ws.getStatus().market) {
await this.connectMarketStream();
}
if (symbol) {
await this.ws.subscribeTicker(symbol);
}
else {
await this.ws.subscribeAllTicker();
}
}
/**
* Subscribe to book ticker
*/
async subscribeBookTicker(symbol) {
if (!this.ws.getStatus().market) {
await this.connectMarketStream();
}
if (symbol) {
await this.ws.subscribeBookTicker(symbol);
}
else {
await this.ws.subscribeAllBookTicker();
}
}
/**
* Subscribe to partial book depth
*/
async subscribeDepth(symbol, levels, updateSpeed = '250ms') {
if (!this.ws.getStatus().market) {
await this.connectMarketStream();
}
await this.ws.subscribePartialBookDepth(symbol, levels, updateSpeed);
}
/**
* Subscribe to mark price updates
*/
async subscribeMarkPrice(symbol, updateSpeed = '1s') {
if (!this.ws.getStatus().market) {
await this.connectMarketStream();
}
if (symbol) {
await this.ws.subscribeMarkPrice(symbol, updateSpeed);
}
else {
await this.ws.subscribeAllMarkPrice(updateSpeed);
}
}
}
exports.BinanceFuturesClient = BinanceFuturesClient;
//# sourceMappingURL=client.js.map