binance-futures-wrapper
v1.0.2
Published
A comprehensive TypeScript wrapper for Binance USDT-M Futures API with full REST and WebSocket support
Maintainers
Readme
Binance Futures Wrapper
A comprehensive TypeScript wrapper for the Binance USDⓈ-M Futures API with full REST and WebSocket support.
Features
- 🚀 Complete API Coverage: Full support for all Binance USDⓈ-M Futures REST and WebSocket APIs
- 🔐 Type-Safe: Built with TypeScript for full type safety and excellent IDE support
- 🔄 Auto-Reconnect: WebSocket connections with automatic reconnection and error handling
- 📡 Real-Time Data: Live market data and user account updates via WebSocket streams
- 🛡️ Built-in Security: Automatic request signing with HMAC SHA256 and timestamp handling
- ⚡ Rate Limiting: Built-in rate limiting to prevent API limits
- 🎯 Easy to Use: Simple, intuitive API with comprehensive examples
- 🧪 Testnet Support: Full support for Binance testnet environment
- 📝 Extensive Documentation: Complete JSDoc documentation for all methods
- 🔧 Modular Design: Use individual components (REST only, WebSocket only, or both)
- 🆕 Latest API Compliance: Fully compliant with latest Binance API requirements including all mandatory parameters
Installation
npm install binance-futures-wrapperQuick Start
Basic Market Data
import { BinanceFuturesClient } from 'binance-futures-wrapper';
const client = new BinanceFuturesClient({
apiKey: 'your_api_key',
apiSecret: 'your_api_secret',
testnet: true // Use testnet for testing
});
// Get current price
const price = await client.getPrice('BTCUSDT');
console.log('BTC Price:', price.price);
// Get order book
const orderBook = await client.getOrderBook('BTCUSDT', 10);
console.log('Best bid:', orderBook.bids[0]);
console.log('Best ask:', orderBook.asks[0]);WebSocket Market Data
import { BinanceFuturesClient } from 'binance-futures-wrapper';
const client = new BinanceFuturesClient({
apiKey: 'your_api_key',
apiSecret: 'your_api_secret',
testnet: true
});
// Set up event handlers
client.on('marketData', (data) => {
if (data.e === 'aggTrade') {
console.log(`${data.s} Trade: ${data.p} (${data.q})`);
}
});
// Connect and subscribe
await client.connectMarketStream();
await client.subscribeAggTrades('BTCUSDT');Account & Trading
// Get account information
const account = await client.getAccount();
console.log('Available Balance:', account.availableBalance);
// Place a limit order with enhanced parameters
const order = await client.createOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
quantity: '0.001',
price: '30000',
timeInForce: 'GTC',
newOrderRespType: 'RESULT', // Get full order response
selfTradePreventionMode: 'EXPIRE_TAKER' // Prevent self-trading
});
// Place a GTD (Good Till Date) order
const gtdOrder = await client.createOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
quantity: '0.001',
price: '29000',
timeInForce: 'GTD',
goodTillDate: Date.now() + (24 * 60 * 60 * 1000) // 24 hours from now
});
// Place a trailing stop market order
const trailingStop = await client.createOrder({
symbol: 'BTCUSDT',
side: 'SELL',
type: 'TRAILING_STOP_MARKET',
quantity: '0.001',
callbackRate: '1.0', // 1% callback rate
activationPrice: '31000' // Optional activation price
});
// Get positions
const positions = await client.getPositions();
console.log('Active positions:', positions.filter(p => parseFloat(p.positionAmt) !== 0));User Data Stream
const client = new BinanceFuturesClient({
apiKey: 'your_api_key',
apiSecret: 'your_api_secret',
testnet: true,
autoConnectUserStream: true // Auto-connect user data stream
});
// Listen for account updates
client.on('userData', (data) => {
if (data.e === 'ORDER_TRADE_UPDATE') {
console.log('Order update:', data.o.s, data.o.X);
} else if (data.e === 'ACCOUNT_UPDATE') {
console.log('Account balance updated');
}
});
await client.initialize();Configuration
interface BinanceFuturesClientConfig {
apiKey: string;
apiSecret: string;
testnet?: boolean; // Default: false
baseURL?: string; // Custom REST API base URL
wsBaseURL?: string; // Custom WebSocket base URL
recvWindow?: number; // Default: 5000ms
enableLogging?: boolean; // Default: false
autoConnectUserStream?: boolean; // Default: false
wsConfig?: {
reconnect?: boolean; // Default: true
reconnectInterval?: number; // Default: 5000ms
maxReconnectAttempts?: number; // Default: 10
keepAlive?: boolean; // Default: true
keepAliveInterval?: number; // Default: 30000ms
};
}API Methods
Market Data
getServerTime()- Get server timegetExchangeInfo()- Get exchange informationgetOrderBook(symbol, limit?)- Get order bookgetRecentTrades(symbol, limit?)- Get recent tradesgetKlines(symbol, interval, limit?, startTime?, endTime?)- Get kline dataget24hrTicker(symbol?)- Get 24hr ticker statisticsgetPrice(symbol?)- Get latest pricegetBookTicker(symbol?)- Get best bid/ask
Account & Trading
getAccount()- Get account information with enhanced balance detailsgetBalance()- Get account balancegetPositions(symbol?)- Get positionscreateOrder(params)- Place new order with full API compliance- Supports all order types:
LIMIT,MARKET,STOP,STOP_MARKET,TAKE_PROFIT,TAKE_PROFIT_MARKET,TRAILING_STOP_MARKET - Enhanced parameters:
priceMatch,selfTradePreventionMode,goodTillDate,newOrderRespType - Time in force options:
GTC,IOC,FOK,GTX,GTD
- Supports all order types:
cancelOrder(params)- Cancel ordercancelAllOrders(symbol)- Cancel all orders for symbolgetOrder(params)- Get order statusgetOpenOrders(symbol?)- Get open ordersgetAllOrders(params)- Get all orderschangeleverage(symbol, leverage)- Change leveragechangeMarginType(symbol, marginType)- Change margin type
Advanced Trading Features
- Self-Trade Prevention: Prevent orders from trading against your own orders
- Price Matching: Use opponent or queue price matching for better execution
- GTD Orders: Set specific expiration times for orders
- Trailing Stop: Dynamic stop-loss orders that follow price movements
- Enhanced Order Response: Get detailed order execution information
WebSocket Subscriptions
subscribeAggTrades(symbol)- Aggregate trade streamssubscribeKlines(symbol, interval)- Kline/candlestick streamssubscribeTicker(symbol?)- 24hr ticker statisticssubscribeBookTicker(symbol?)- Best bid/ask streamssubscribeDepth(symbol, levels, updateSpeed?)- Order book depthsubscribeMarkPrice(symbol?, updateSpeed?)- Mark price streams
Events
The client extends EventEmitter and emits the following events:
Connection Events
'marketConnected'- Market WebSocket connected'marketDisconnected'- Market WebSocket disconnected'userConnected'- User data stream connected'userDisconnected'- User data stream disconnected
Data Events
'marketData'- Market data received'userData'- User data received'error'- Error occurred
Examples
See the examples/ directory for complete examples:
basic-usage.ts- Basic market data operationswebsocket-market.ts- Real-time market datatrading.ts- Trading operations with enhanced parametersuser-data-stream.ts- Real-time account updatestype-safe-websocket.ts- Type-safe WebSocket usage
Advanced Order Examples
// GTD Order with specific expiration
const gtdOrder = await client.createOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
quantity: '0.01',
price: '29000',
timeInForce: 'GTD',
goodTillDate: Date.now() + (24 * 60 * 60 * 1000), // Expires in 24 hours
selfTradePreventionMode: 'EXPIRE_BOTH'
});
// Trailing Stop with activation price
const trailingStop = await client.createOrder({
symbol: 'BTCUSDT',
side: 'SELL',
type: 'TRAILING_STOP_MARKET',
quantity: '0.01',
callbackRate: '2.0', // 2% callback
activationPrice: '32000',
newOrderRespType: 'RESULT'
});
// Price matching order
const priceMatchOrder = await client.createOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'LIMIT',
quantity: '0.01',
// Don't set price when using priceMatch
priceMatch: 'OPPONENT_5', // Match opponent price with 5 levels
timeInForce: 'IOC'
});Error Handling
The library includes comprehensive error handling with specific Binance error codes:
try {
const order = await client.createOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'MARKET',
quantity: '0.001'
});
} catch (error) {
if (error.code) {
console.log('Binance error code:', error.code);
console.log('Error message:', error.message);
// Handle specific error codes
switch (error.code) {
case -1102:
console.log('Mandatory parameter missing or malformed');
break;
case -2010:
console.log('New order rejected');
break;
case -4164:
console.log('Order notional too small');
break;
default:
console.log('Other Binance API error');
}
} else {
console.log('Network or other error:', error.message);
}
}Common Error Codes
-1102: Mandatory parameter missing or malformed-1106: Parameter sent when not required-2010: New order rejected-2021: Order would immediately trigger-4164: Order's notional must be no smaller than minimum requirement-4046: No need to change margin type
Rate Limiting
The library automatically handles rate limiting to prevent exceeding Binance API limits. Each endpoint has appropriate weights assigned and the client manages the request rate accordingly.
WebSocket Reconnection
WebSocket connections include automatic reconnection with exponential backoff:
- Automatic reconnection on connection loss
- Automatic resubscription to previous streams
- Configurable retry attempts and intervals
- Connection state management
Security
- All authenticated requests are automatically signed with HMAC SHA256
- API keys are never logged or exposed
- Timestamps are automatically managed and validated
- Request/response validation with proper parameter handling
- Automatic
recvWindowandtimestampparameter injection - Full compliance with Binance security requirements
API Compliance
This wrapper is fully compliant with the latest Binance USDⓈ-M Futures API specification:
- ✅ All mandatory parameters automatically included (
timestamp,recvWindow) - ✅ Proper request formatting (
application/x-www-form-urlencoded) - ✅ Complete parameter validation and type checking
- ✅ Support for all order types and advanced features
- ✅ Enhanced error handling with specific Binance error codes
- ✅ Rate limiting compliance to prevent API restrictions
TypeScript Support
The library is built with TypeScript and provides complete type definitions:
import {
BinanceFuturesClient,
OrderSideType,
OrderTypeType,
PositionSideType,
TimeInForceType,
NewOrderParams
} from 'binance-futures-wrapper';
// Full type safety for all parameters and responses
const order: NewOrderParams = {
symbol: 'BTCUSDT',
side: 'BUY' as OrderSideType,
type: 'LIMIT' as OrderTypeType,
quantity: '0.001',
price: '30000',
timeInForce: 'GTC' as TimeInForceType,
newOrderRespType: 'RESULT',
selfTradePreventionMode: 'EXPIRE_TAKER',
priceMatch: 'QUEUE'
};
// Enhanced order creation with full parameter support
const advancedOrder = await client.createOrder({
symbol: 'BTCUSDT',
side: 'BUY',
type: 'TRAILING_STOP_MARKET',
quantity: '0.001',
callbackRate: '1.5',
activationPrice: '30000',
workingType: 'MARK_PRICE',
newOrderRespType: 'RESULT'
});Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests for any improvements.
License
MIT License - see LICENSE file for details.
Disclaimer
This library is not officially affiliated with Binance. Use at your own risk. Always test thoroughly with small amounts and on testnet before using with real funds.
Support
- Create an issue for bug reports or feature requests
- Check existing issues before creating new ones
- Provide minimal reproduction examples for bugs
Changelog
v1.1.0 - Latest API Compliance Update
- ✅ Full Binance USDⓈ-M Futures API Compliance: Updated to match latest API specification
- 🆕 Enhanced Order Parameters: Added
priceMatch,selfTradePreventionMode,goodTillDate,newOrderRespType - 🆕 GTD Order Support: Full support for Good Till Date orders with automatic timestamp handling
- 🆕 Trailing Stop Market: Complete implementation of trailing stop market orders
- 🔧 Request Format Fix: Changed to proper
application/x-www-form-urlencodedformat - 🔧 Automatic Parameter Injection: All signed endpoints now automatically include
timestampandrecvWindow - 🔧 Enhanced Type Safety: Updated TypeScript interfaces with all new parameters
- 🔧 Better Error Handling: Improved error messages and Binance error code handling
- 📝 Updated Documentation: Comprehensive examples and parameter documentation
v1.0.0
- Initial release
- Complete REST API support
- Full WebSocket support
- TypeScript types
- Comprehensive examples
- Auto-reconnection
- Rate limiting
- User data streams
