UNPKG

binance-futures-wrapper

Version:

A comprehensive TypeScript wrapper for Binance USDT-M Futures API with full REST and WebSocket support

429 lines (348 loc) โ€ข 13.7 kB
# 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 ```bash npm install binance-futures-wrapper ``` ## Quick Start ### Basic Market Data ```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]); ``` ### WebSocket Market Data ```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'); ``` ### Account & Trading ```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)); ``` ### User Data Stream ```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(); ``` ## Configuration ```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 }; } ``` ## API Methods ### Market Data - `getServerTime()` - Get server time - `getExchangeInfo()` - Get exchange information - `getOrderBook(symbol, limit?)` - Get order book - `getRecentTrades(symbol, limit?)` - Get recent trades - `getKlines(symbol, interval, limit?, startTime?, endTime?)` - Get kline data - `get24hrTicker(symbol?)` - Get 24hr ticker statistics - `getPrice(symbol?)` - Get latest price - `getBookTicker(symbol?)` - Get best bid/ask ### Account & Trading - `getAccount()` - Get account information with enhanced balance details - `getBalance()` - Get account balance - `getPositions(symbol?)` - Get positions - `createOrder(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` - `cancelOrder(params)` - Cancel order - `cancelAllOrders(symbol)` - Cancel all orders for symbol - `getOrder(params)` - Get order status - `getOpenOrders(symbol?)` - Get open orders - `getAllOrders(params)` - Get all orders - `changeleverage(symbol, leverage)` - Change leverage - `changeMarginType(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 streams - `subscribeKlines(symbol, interval)` - Kline/candlestick streams - `subscribeTicker(symbol?)` - 24hr ticker statistics - `subscribeBookTicker(symbol?)` - Best bid/ask streams - `subscribeDepth(symbol, levels, updateSpeed?)` - Order book depth - `subscribeMarkPrice(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`](examples/basic-usage.ts) - Basic market data operations - [`websocket-market.ts`](examples/websocket-market.ts) - Real-time market data - [`trading.ts`](examples/trading.ts) - Trading operations with enhanced parameters - [`user-data-stream.ts`](examples/user-data-stream.ts) - Real-time account updates - [`type-safe-websocket.ts`](examples/type-safe-websocket.ts) - Type-safe WebSocket usage ### Advanced Order Examples ```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); } } ``` ### 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 `recvWindow` and `timestamp` parameter 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: ```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 ### 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-urlencoded` format - ๐Ÿ”ง **Automatic Parameter Injection**: All signed endpoints now automatically include `timestamp` and `recvWindow` - ๐Ÿ”ง **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