A comprehensive TypeScript wrapper for Binance USDT-M Futures API with full REST and WebSocket support
npm install binance-futures-wrapperA comprehensive TypeScript wrapper for the Binance USDโ-M Futures API with full REST and WebSocket support.
- ๐ 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
``bash`
npm install binance-futures-wrapper
`typescript
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]);
`
`typescript
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');
`
`typescript
// 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));
`
`typescript
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();
`
`typescript`
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
};
}
- 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
- getAccount() - Get account information with enhanced balance detailsgetBalance()
- - Get account balancegetPositions(symbol?)
- - Get positionscreateOrder(params)
- - Place new order with full API complianceLIMIT
- Supports all order types: , MARKET, STOP, STOP_MARKET, TAKE_PROFIT, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKETpriceMatch
- Enhanced parameters: , selfTradePreventionMode, goodTillDate, newOrderRespTypeGTC
- Time in force options: , IOC, FOK, GTX, GTDcancelOrder(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
- 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
- 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
The client extends EventEmitter and emits the following events:
- Market WebSocket connected
- 'marketDisconnected' - Market WebSocket disconnected
- 'userConnected' - User data stream connected
- 'userDisconnected' - User data stream disconnected$3
- 'marketData' - Market data received
- 'userData' - User data received
- 'error' - Error occurredExamples
See the
examples/ directory for complete examples:basic-usage.ts - Basic market data operations
- websocket-market.ts - Real-time market data
- trading.ts - Trading operations with enhanced parameters
- user-data-stream.ts - Real-time account updates
- type-safe-websocket.ts - Type-safe WebSocket usage$3
`typescript
// 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:
`typescript
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);
}
}
`$3
-
-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 typeRate 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
recvWindow and timestamp parameter injection
- Full compliance with Binance security requirementsAPI 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 restrictionsTypeScript Support
The library is built with TypeScript and provides complete type definitions:
`typescript
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
$3
- โ
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-urlencoded format
- ๐ง Automatic Parameter Injection: All signed endpoints now automatically include timestamp and recvWindow`