A TypeScript SDK for MEXC Futures trading with REST API and WebSocket support.
- ✅ REST API - Complete trading functionality
- ✅ WebSocket - Real-time market data and account updates
- ✅ TypeScript - Full type definitions
- ✅ Auto-reconnect - Reliable WebSocket connections
- ✅ Error handling - Comprehensive error management
npm install mexc-futures-sdk
import { MexcFuturesClient } from "mexc-futures-sdk";
const client = new MexcFuturesClient({
authToken: "WEB_YOUR_TOKEN_HERE", // Get from browser Developer Tools
});
// Get ticker data
const ticker = await client.getTicker("BTC_USDT");
console.log("BTC Price:", ticker.data.lastPrice);
// Place a market order
const order = await client.submitOrder({
symbol: "BTC_USDT",
price: 50000,
vol: 0.001,
side: 1, // 1=open long, 3=open short
type: 5, // 5=market order
openType: 1, // 1=isolated margin
leverage: 10,
});
import { MexcFuturesWebSocket } from "mexc-futures-sdk";
const ws = new MexcFuturesWebSocket({
apiKey: "YOUR_API_KEY",
secretKey: "YOUR_SECRET_KEY",
autoReconnect: true,
});
// Connect and login
ws.on("connected", () => {
ws.login(false).then(() => {
console.log("Login successful");
ws.subscribeToAll(); // Subscribe to all private data
});
});
// Handle trading events
ws.on("orderUpdate", (data) => {
console.log("Order Update:", data.orderId, data.symbol, data.state);
});
ws.on("positionUpdate", (data) => {
console.log("Position:", data.symbol, data.holdVol, data.pnl);
});
ws.on("assetUpdate", (data) => {
console.log("Balance:", data.currency, data.availableBalance);
});
await ws.connect();
- Login to MEXC futures in your browser
- Open Developer Tools (F12) → Network tab
- Make any request to futures.mexc.com
- Find the
authorization
header (starts with "WEB...") - Copy the token value
- Go to MEXC API Management
- Create API Key and Secret
- Enable futures trading permissions
Event | Description | Data |
---|---|---|
orderUpdate |
Order status changes | Order details, state, fills |
orderDeal |
Order executions | Trade details, fees, profit |
positionUpdate |
Position changes | Size, PnL, margin, liquidation price |
assetUpdate |
Balance changes | Available, frozen, position margin |
stopOrder |
Stop-loss/take-profit | Stop prices for positions |
liquidateRisk |
Liquidation warnings | Margin ratio, liquidation price |
Event | Description | Data |
---|---|---|
tickers |
All symbol prices | Price, volume, change for all symbols |
ticker |
Single symbol price | Real-time price updates |
depth |
Order book | Bids and asks |
kline |
Candlestick data | OHLCV data |
deal |
Recent trades | Trade executions |
ws.on("login", () => {
ws.subscribeToAll(); // Get all trading events
});
ws.on("login", () => {
ws.subscribeToMultiple([
{
filter: "order",
rules: ["BTC_USDT", "ETH_USDT"], // Only these symbols
},
{
filter: "position",
rules: ["BTC_USDT", "ETH_USDT"],
},
{
filter: "asset", // All balance updates
},
]);
});
// Subscribe to market data
ws.subscribeToAllTickers(); // All symbol prices
ws.subscribeToTicker("BTC_USDT"); // Single symbol
ws.subscribeToDepth("BTC_USDT"); // Order book
ws.subscribeToKline("BTC_USDT", "Min1"); // 1-minute candles
1
= Open long position2
= Close short position3
= Open short position4
= Close long position
1
= Limit order5
= Market order3
= IOC (Immediate or Cancel)4
= FOK (Fill or Kill)
1
= New2
= Pending3
= Filled4
= Cancelled
// Market order
await client.submitOrder({
symbol: "BTC_USDT",
price: 50000, // Required even for market orders
vol: 0.001,
side: 1, // Open long
type: 5, // Market
openType: 1, // Isolated margin
leverage: 10,
});
// Limit order with stop-loss
await client.submitOrder({
symbol: "BTC_USDT",
price: 49000,
vol: 0.001,
side: 1, // Open long
type: 1, // Limit
openType: 1, // Isolated margin
leverage: 10,
stopLossPrice: 45000,
takeProfitPrice: 55000,
});
// Close position
await client.submitOrder({
symbol: "BTC_USDT",
price: 51000,
vol: 0.001,
side: 4, // Close long
type: 5, // Market
openType: 1,
positionId: 12345, // Position to close
});
The SDK provides comprehensive error handling with user-friendly error messages and specific error types.
import {
MexcAuthenticationError,
MexcSignatureError,
MexcApiError,
MexcNetworkError,
MexcValidationError,
MexcRateLimitError,
MexcFuturesError,
} from "mexc-futures-sdk";
try {
const asset = await client.getAccountAsset("USDT");
console.log("Success:", asset);
} catch (error) {
if (error instanceof MexcAuthenticationError) {
console.log("❌ Authentication failed. Please update your WEB token.");
} else if (error instanceof MexcSignatureError) {
console.log("❌ Signature verification failed. Get a fresh WEB token.");
} else if (error instanceof MexcRateLimitError) {
console.log("❌ Rate limit exceeded. Please wait before retrying.");
if (error.retryAfter) {
console.log(`Retry after ${error.retryAfter} seconds`);
}
} else if (error instanceof MexcNetworkError) {
console.log("❌ Network error. Check your internet connection.");
} else if (error instanceof MexcValidationError) {
console.log(`❌ Validation error: ${error.message}`);
} else if (error instanceof MexcApiError) {
console.log(`❌ API error (${error.statusCode}): ${error.message}`);
}
// Get detailed error information for debugging
if (error instanceof MexcFuturesError) {
console.log("Error details:", error.getDetails());
}
}
All errors provide user-friendly messages through getUserFriendlyMessage()
:
try {
await client.submitOrder({...});
} catch (error) {
if (error instanceof MexcFuturesError) {
console.log(error.getUserFriendlyMessage());
// Example: "❌ Authentication failed. Your authorization token may be expired or invalid. Please update your WEB token from browser Developer Tools."
}
}
Error Type | Common Causes | Solutions |
---|---|---|
MexcAuthenticationError |
Invalid/expired WEB token | Get fresh token from browser |
MexcSignatureError |
Token authentication failed | Update WEB token |
MexcRateLimitError |
Too many requests | Wait and retry |
MexcNetworkError |
Connection issues | Check internet connection |
MexcValidationError |
Invalid parameters | Check request parameters |
ws.on("error", (error) => {
console.error("WebSocket error:", error);
});
ws.on("disconnected", ({ code, reason }) => {
console.log("Disconnected:", code, reason);
});
Set logLevel
to control error verbosity:
const client = new MexcFuturesClient({
authToken: "WEB_YOUR_TOKEN",
logLevel: "INFO", // "SILENT", "ERROR", "WARN", "INFO", "DEBUG"
});
ERROR
: Only error messagesINFO
: User-friendly error messagesDEBUG
: Detailed error information for debugging
See examples/websocket.ts
for a complete working example with:
- Connection management
- Event handlers for all data types
- Error handling
- Graceful shutdown
# Run the example
npm install
ts-node examples/websocket.ts
getTicker(symbol)
- Get ticker datagetContractDetail(symbol?)
- Get contract infogetContractDepth(symbol, limit?)
- Get order booksubmitOrder(params)
- Place ordercancelOrder(orderIds)
- Cancel ordersgetOrderHistory(params)
- Get order historygetPositionHistory(params)
- Get position historygetAssets()
- Get account balance
connect()
- Connect to WebSocketlogin(subscribe?)
- Login and optionally auto-subscribesubscribeToAll()
- Subscribe to all private datasubscribeToMultiple(filters)
- Subscribe with filterssubscribeToTicker(symbol)
- Market data subscriptionsdisconnect()
- Close connection
This is an unofficial SDK. Use at your own risk. For issues and feature requests, please open a GitHub issue.
MIT