binance-futures-wrapper
Version:
A comprehensive TypeScript wrapper for Binance USDT-M Futures API with full REST and WebSocket support
404 lines • 11.6 kB
JavaScript
"use strict";
/**
* REST API client for Binance Futures
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestClient = void 0;
const axios_1 = __importDefault(require("axios"));
const utils_1 = require("../utils");
const endpoints_1 = require("./endpoints");
class RestClient {
constructor(config) {
(0, utils_1.validateConfig)(config);
this.config = {
recvWindow: 5000,
enableLogging: false,
testnet: false,
...config
};
const baseUrls = (0, utils_1.getBaseUrls)(this.config.testnet);
this.baseUrl = this.config.baseURL || baseUrls.rest;
this.logger = new utils_1.Logger(this.config.enableLogging, '[RestClient]');
this.rateLimiter = new utils_1.RateLimiter();
const headers = {};
// Only add API key header if provided
if (this.config.apiKey) {
headers['X-MBX-APIKEY'] = this.config.apiKey;
}
this.client = axios_1.default.create({
baseURL: this.baseUrl,
timeout: 10000,
headers
});
this.setupInterceptors();
}
setupInterceptors() {
// Request interceptor
this.client.interceptors.request.use((config) => {
this.logger.debug(`Request: ${config.method?.toUpperCase()} ${config.url}`, {
params: config.params,
data: config.data
});
return config;
}, (error) => {
this.logger.error('Request error:', error);
return Promise.reject(error);
});
// Response interceptor
this.client.interceptors.response.use((response) => {
this.logger.debug(`Response: ${response.status} ${response.config.url}`, {
data: response.data
});
return response;
}, (error) => {
this.logger.error('Response error:', {
status: error.response?.status,
data: error.response?.data,
url: error.config?.url
});
return Promise.reject(this.handleError(error));
});
}
handleError(error) {
if (error.response) {
const { status, data } = error.response;
const message = data?.msg || data?.message || `HTTP ${status}`;
const binanceError = new Error(message);
binanceError.code = data?.code;
binanceError.status = status;
return binanceError;
}
if (error.request) {
return new Error('Network error: No response received');
}
return error;
}
/**
* Generic request method
*/
async request(method, endpoint, params = {}, signed = false) {
await this.rateLimiter.checkLimit();
let finalParams = { ...params };
if (signed) {
if (!this.config.apiKey || !this.config.apiSecret) {
throw new Error('API key and secret are required for signed requests');
}
finalParams.recvWindow = this.config.recvWindow;
finalParams = (0, utils_1.addSignature)(finalParams, this.config.apiSecret);
}
const config = {
method,
url: endpoint
};
if (method === 'GET' || method === 'DELETE') {
config.params = finalParams;
}
else {
// For POST/PUT requests, send as URL encoded data
config.data = (0, utils_1.objectToQueryString)(finalParams);
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
}
const response = await this.client.request(config);
return response.data;
}
/**
* Call predefined endpoint
*/
async call(endpointKey, params = {}) {
const endpoint = endpoints_1.ENDPOINTS[endpointKey];
if (!endpoint) {
throw new Error(`Unknown endpoint: ${endpointKey}`);
}
return this.request(endpoint.method, endpoint.path, params, endpoint.signed);
}
// Market Data Methods
/**
* Test connectivity to the Rest API
*/
async ping() {
return this.call('PING');
}
/**
* Test connectivity to the Rest API and get the current server time
*/
async time() {
return this.call('TIME');
}
/**
* Current exchange trading rules and symbol information
*/
async exchangeInfo() {
return this.call('EXCHANGE_INFO');
}
/**
* Get orderbook for symbol
*/
async orderBook(params) {
return this.call('ORDER_BOOK', params);
}
/**
* Get recent trades list
*/
async trades(params) {
return this.call('TRADES', params);
}
/**
* Get older market trades
*/
async historicalTrades(params) {
return this.call('HISTORICAL_TRADES', params);
}
/**
* Get compressed, aggregate trades
*/
async aggTrades(params) {
return this.call('AGG_TRADES', params);
}
/**
* Kline/candlestick bars for a symbol
*/
async klines(params) {
const rawData = await this.call('KLINES', params);
return (0, utils_1.convertKlinesData)(rawData);
}
/**
* Continuous contract kline/candlestick bars for a pair
*/
async continuousKlines(params) {
const rawData = await this.call('CONTINUOUS_KLINES', params);
return (0, utils_1.convertKlinesData)(rawData);
}
/**
* Index price kline/candlestick bars for a pair
*/
async indexPriceKlines(params) {
const rawData = await this.call('INDEX_PRICE_KLINES', params);
return (0, utils_1.convertKlinesData)(rawData);
}
/**
* Mark price kline/candlestick bars for a symbol
*/
async markPriceKlines(params) {
const rawData = await this.call('MARK_PRICE_KLINES', params);
return (0, utils_1.convertKlinesData)(rawData);
}
/**
* Mark Price and Funding Rate
*/
async markPrice(params) {
return this.call('MARK_PRICE', params);
}
/**
* Get funding rate history
*/
async fundingRate(params) {
return this.call('FUNDING_RATE', params);
}
/**
* 24hr ticker price change statistics
*/
async ticker24hr(params) {
return this.call('TICKER_24HR', params);
}
/**
* Latest price for a symbol or symbols
*/
async tickerPrice(params) {
return this.call('TICKER_PRICE', params);
}
/**
* Best price/qty on the order book for a symbol or symbols
*/
async bookTicker(params) {
return this.call('TICKER_BOOK', params);
}
/**
* Get present open interest of a specific symbol
*/
async openInterest(params) {
return this.call('OPEN_INTEREST', params);
}
// Account/Trade Methods
/**
* Change user's position mode (Hedge Mode or One-way Mode) on EVERY symbol
*/
async changePositionMode(params) {
return this.call('POSITION_MODE', params);
}
/**
* Get user's position mode (Hedge Mode or One-way Mode) on EVERY symbol
*/
async getPositionMode() {
return this.call('GET_POSITION_MODE');
}
/**
* Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol
*/
async changeMultiAssetsMode(params) {
return this.call('MULTI_ASSETS_MODE', params);
}
/**
* Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol
*/
async getMultiAssetsMode() {
return this.call('GET_MULTI_ASSETS_MODE');
}
/**
* Send in a new order
*/
async newOrder(params) {
return this.call('ORDER', params);
}
/**
* Modify an open order
*/
async modifyOrder(params) {
return this.call('MODIFY_ORDER', params);
}
/**
* Place multiple orders
*/
async newBatchOrders(params) {
return this.call('BATCH_ORDERS', params);
}
/**
* Check an order's status
*/
async getOrder(params) {
return this.call('GET_ORDER', params);
}
/**
* Cancel an active order
*/
async cancelOrder(params) {
return this.call('CANCEL_ORDER', params);
}
/**
* Cancel all open orders for a symbol
*/
async cancelAllOrders(params) {
return this.call('CANCEL_ALL_ORDERS', params);
}
/**
* Cancel multiple orders
*/
async cancelBatchOrders(params) {
return this.call('CANCEL_BATCH_ORDERS', params);
}
/**
* Get all open orders on a symbol
*/
async getOpenOrders(params) {
return this.call('GET_OPEN_ORDERS', params);
}
/**
* Get all account orders; active, canceled, or filled
*/
async getAllOrders(params) {
return this.call('GET_ALL_ORDERS', params);
}
/**
* Get futures account balance
*/
async balance() {
return this.call('BALANCE');
}
/**
* Get current account information
*/
async account() {
return this.call('ACCOUNT');
}
/**
* Change user's initial leverage of specific symbol market
*/
async changeInitialLeverage(params) {
return this.call('LEVERAGE', params);
}
/**
* Change user's margin type of specific symbol market
*/
async changeMarginType(params) {
return this.call('MARGIN_TYPE', params);
}
/**
* Modify isolated position margin
*/
async modifyPositionMargin(params) {
return this.call('POSITION_MARGIN', params);
}
/**
* Get position margin change history
*/
async getPositionMarginHistory(params) {
return this.call('POSITION_MARGIN_HISTORY', params);
}
/**
* Get current position information
*/
async positionRisk(params) {
return this.call('POSITION_RISK', params);
}
/**
* Get trades for a specific account and symbol
*/
async userTrades(params) {
return this.call('USER_TRADES', params);
}
/**
* Get income history
*/
async getIncomeHistory(params) {
return this.call('INCOME', params);
}
/**
* Notional and Leverage Brackets
*/
async leverageBracket(params) {
return this.call('LEVERAGE_BRACKET', params);
}
/**
* Position ADL Quantile Estimation
*/
async adlQuantile(params) {
return this.call('ADL_QUANTILE', params);
}
/**
* User's Force Orders
*/
async forceOrders(params) {
return this.call('FORCE_ORDERS', params);
}
/**
* User API Trading Quantitative Rules Indicators
*/
async apiTradingStatus() {
return this.call('API_TRADING_STATUS');
}
// User Data Stream Methods
/**
* Start a new user data stream
*/
async createListenKey() {
return this.call('USER_STREAM_START');
}
/**
* Keepalive a user data stream to prevent a time out
*/
async keepaliveListenKey(params) {
return this.call('USER_STREAM_KEEPALIVE', params);
}
/**
* Close out a user data stream
*/
async closeListenKey(params) {
return this.call('USER_STREAM_CLOSE', params);
}
}
exports.RestClient = RestClient;
//# sourceMappingURL=client.js.map