npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

binance-futures-wrapper

v1.0.2

Published

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

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-wrapper

Quick 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 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:

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 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:

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