MEXC API Endpoints Reference for Crypto Traders
Complete guide to MEXC API endpoints: authentication, market data, order management, and code examples for algo traders building bots.
Complete guide to MEXC API endpoints: authentication, market data, order management, and code examples for algo traders building bots.
MEXC has quietly become one of the more trader-friendly exchanges when it comes to API access. With over 1,500 spot pairs and a futures market that rivals Binance and Bybit in terms of breadth, it attracts algorithmic traders who want deep liquidity without fighting for access. The REST API is well-documented, rate limits are generous compared to competitors, and the WebSocket feed is stable enough for production bots. Whether you're building a market-making strategy, connecting a signal aggregator like VoiceOfChain, or just automating your own entries — understanding the MEXC endpoint structure is step one.
MEXC exposes two main interfaces: a REST API for request-response operations and a WebSocket API for real-time streaming. The base URL for the REST API is https://api.mexc.com, with the v3 versioned path being the current stable release. Spot and futures endpoints are separated — spot lives under /api/v3/ while futures (contract trading) uses /api/v1/private/ and /api/v1/public/ namespaces.
| Category | Base Path | Auth Required |
|---|---|---|
| Market Data | /api/v3/ticker, /depth, /klines | No |
| Account Info | /api/v3/account | Yes |
| Order Management | /api/v3/order | Yes |
| Trade History | /api/v3/myTrades | Yes |
| WebSocket Streams | wss://wbs.mexc.com/ws | Optional |
Public endpoints like market data and order book depth require no credentials. Authenticated endpoints use HMAC-SHA256 signatures — the same pattern you'll recognize if you've worked with Binance or OKX APIs. This consistency is deliberate and makes it straightforward to port bots between exchanges.
Before hitting any private endpoint, you need an API key pair from your MEXC account settings. Navigate to the API Management section, create a key with the permissions your strategy needs (read-only for monitoring, trade permissions for execution), and whitelist your server IP. Never give withdrawal permissions to a trading key — this is as true on MEXC as it is on Bybit, Gate.io, or any other exchange.
MEXC authentication works by appending a signature to every private request. The signature is a HMAC-SHA256 hash of the full query string (including a timestamp parameter) using your secret key. The timestamp must be within 5000 milliseconds of server time — worth checking server time via /api/v3/time if your bot runs on a machine with drifted clocks.
import hmac
import hashlib
import time
import requests
API_KEY = 'your_api_key_here'
SECRET_KEY = 'your_secret_key_here'
BASE_URL = 'https://api.mexc.com'
def get_signature(params: dict, secret: str) -> str:
query_string = '&'.join([f'{k}={v}' for k, v in sorted(params.items())])
return hmac.new(
secret.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
def get_account_info():
endpoint = '/api/v3/account'
params = {
'timestamp': int(time.time() * 1000),
'recvWindow': 5000
}
params['signature'] = get_signature(params, SECRET_KEY)
headers = {'X-MEXC-APIKEY': API_KEY}
response = requests.get(
BASE_URL + endpoint,
params=params,
headers=headers
)
response.raise_for_status()
return response.json()
account = get_account_info()
print(f"Account balances: {len(account['balances'])} assets")
Store API keys in environment variables or a secrets manager — never hardcode them in source files. If you're connecting a signal service like VoiceOfChain to MEXC, use read-only keys for balance monitoring and a separate trade-enabled key only for order execution.
The market data endpoints are the backbone of any trading system. No authentication needed, high rate limits, and the data is solid. Here are the endpoints you'll use most frequently as a trader or bot developer.
import requests
import pandas as pd
from datetime import datetime
BASE_URL = 'https://api.mexc.com'
def get_klines(symbol: str, interval: str = '1h', limit: int = 100) -> pd.DataFrame:
"""
Fetch OHLCV candles from MEXC.
interval options: 1m, 5m, 15m, 30m, 60m, 4h, 1d, 1W, 1M
"""
endpoint = '/api/v3/klines'
params = {
'symbol': symbol,
'interval': interval,
'limit': limit
}
response = requests.get(BASE_URL + endpoint, params=params)
response.raise_for_status()
data = response.json()
df = pd.DataFrame(data, columns=[
'open_time', 'open', 'high', 'low', 'close', 'volume',
'close_time', 'quote_volume', 'trades_count',
'taker_buy_base', 'taker_buy_quote', 'ignore'
])
df['open_time'] = pd.to_datetime(df['open_time'], unit='ms')
df['close_time'] = pd.to_datetime(df['close_time'], unit='ms')
for col in ['open', 'high', 'low', 'close', 'volume']:
df[col] = df[col].astype(float)
return df[['open_time', 'open', 'high', 'low', 'close', 'volume']]
# Example: fetch BTC/USDT hourly candles
btc_candles = get_klines('BTCUSDT', '1h', 200)
print(btc_candles.tail())
print(f"Latest close: ${btc_candles['close'].iloc[-1]:,.2f}")
The klines endpoint response format matches Binance's structure almost exactly — a deliberate design choice that makes cross-exchange development easier. If you're running a multi-exchange strategy across MEXC, Bybit, and KuCoin, you can often reuse the same parsing logic with minimal modification.
Order endpoints are where real money moves, so error handling isn't optional. MEXC's order API follows standard REST conventions — POST to create, GET to query, DELETE to cancel. The key endpoint is /api/v3/order, which handles all spot order types: LIMIT, MARKET, LIMIT_MAKER, and IMMEDIATE_OR_CANCEL.
import hmac
import hashlib
import time
import requests
from enum import Enum
API_KEY = 'your_api_key_here'
SECRET_KEY = 'your_secret_key_here'
BASE_URL = 'https://api.mexc.com'
class OrderSide(str, Enum):
BUY = 'BUY'
SELL = 'SELL'
class OrderType(str, Enum):
LIMIT = 'LIMIT'
MARKET = 'MARKET'
def sign_params(params: dict) -> dict:
query = '&'.join([f'{k}={v}' for k, v in sorted(params.items())])
sig = hmac.new(
SECRET_KEY.encode(),
query.encode(),
hashlib.sha256
).hexdigest()
return {**params, 'signature': sig}
def place_limit_order(
symbol: str,
side: OrderSide,
quantity: float,
price: float
) -> dict:
params = sign_params({
'symbol': symbol,
'side': side.value,
'type': OrderType.LIMIT.value,
'quantity': quantity,
'price': price,
'timeInForce': 'GTC',
'timestamp': int(time.time() * 1000)
})
headers = {'X-MEXC-APIKEY': API_KEY}
try:
response = requests.post(
BASE_URL + '/api/v3/order',
params=params,
headers=headers
)
response.raise_for_status()
order = response.json()
print(f"Order placed: {order['orderId']} | Status: {order['status']}")
return order
except requests.exceptions.HTTPError as e:
error_data = e.response.json()
print(f"Order failed: [{error_data['code']}] {error_data['msg']}")
raise
def cancel_order(symbol: str, order_id: str) -> dict:
params = sign_params({
'symbol': symbol,
'orderId': order_id,
'timestamp': int(time.time() * 1000)
})
headers = {'X-MEXC-APIKEY': API_KEY}
response = requests.delete(
BASE_URL + '/api/v3/order',
params=params,
headers=headers
)
response.raise_for_status()
return response.json()
# Place a limit buy order
# order = place_limit_order('ETHUSDT', OrderSide.BUY, quantity=0.1, price=3000.0)
MEXC error code -1121 means invalid symbol — always validate symbol format (e.g., 'BTCUSDT' not 'BTC/USDT') before sending orders. Error -2010 is insufficient balance. Build explicit handlers for both — silent failures in order bots cause real losses.
For checking open orders, use GET /api/v3/openOrders with a symbol parameter. For full order history, GET /api/v3/allOrders returns everything with optional time range filtering. Both are paginated — use the fromId parameter for efficient pagination rather than pulling everything on each poll cycle.
Polling REST endpoints for price updates is inefficient and burns rate limit budget fast. MEXC's WebSocket API delivers real-time streams for trades, order book updates, candlestick data, and account events. The connection endpoint is wss://wbs.mexc.com/ws — a single connection can handle multiple stream subscriptions.
Compared to platforms like Binance or OKX which use separate stream URLs per data type, MEXC uses a subscription message model where you send JSON subscription commands after connecting. This is actually cleaner for managing multiple symbols in one bot.
const WebSocket = require('ws');
const WS_URL = 'wss://wbs.mexc.com/ws';
function createMexcStream(symbols, callback) {
const ws = new WebSocket(WS_URL);
ws.on('open', () => {
console.log('Connected to MEXC WebSocket');
// Subscribe to mini ticker for multiple symbols
const subscribeMsg = {
method: 'SUBSCRIPTION',
params: symbols.map(s => `[email protected]@UTC+0`)
};
// Subscribe to individual trade streams
symbols.forEach(symbol => {
ws.send(JSON.stringify({
method: 'SUBSCRIPTION',
params: [`[email protected]@${symbol}`]
}));
});
});
ws.on('message', (data) => {
try {
const msg = JSON.parse(data);
if (msg.d && msg.c) {
callback(msg);
}
} catch (err) {
console.error('Parse error:', err.message);
}
});
ws.on('close', () => {
console.log('WebSocket closed — reconnecting in 5s');
setTimeout(() => createMexcStream(symbols, callback), 5000);
});
ws.on('error', (err) => {
console.error('WebSocket error:', err.message);
});
// Keepalive ping every 20 seconds
const pingInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ method: 'PING' }));
}
}, 20000);
ws.on('close', () => clearInterval(pingInterval));
return ws;
}
// Example usage
const stream = createMexcStream(
['BTCUSDT', 'ETHUSDT'],
(msg) => {
console.log(`[${msg.c}] Price update:`, JSON.stringify(msg.d, null, 2));
}
);
VoiceOfChain uses WebSocket connections like this to ingest real-time price data across multiple exchanges simultaneously, feeding its signal engine without the latency overhead of REST polling. For time-sensitive strategies — scalping, momentum entries, liquidation cascade plays — WebSocket is non-negotiable. REST is for setup and order management; WebSocket is for everything time-critical.
MEXC's rate limits are more generous than most. The default is 20 requests per second for order endpoints and 500 requests per second for market data. Compare that to Binance's 1200 per minute (20/sec) for orders and you'll see they're roughly equivalent — but MEXC has lighter burst penalties. Still, production bots need to implement rate limiting explicitly.
One pattern worth adopting early: maintain a local order state cache synchronized via WebSocket user data streams rather than polling /api/v3/order on every tick. This single change typically cuts private API usage by 80% in trading bots. Platforms like Bybit, Bitget, and Gate.io all support equivalent user data streams — it's a universal best practice, not MEXC-specific.
MEXC's API is one of the cleaner implementations in the exchange ecosystem. The Binance-compatible structure means your existing tooling likely works with minimal adaptation, the rate limits are production-friendly, and the WebSocket feed is reliable enough for real strategies. The key to using it well is the same as any exchange API: keep REST for management operations, use WebSocket for real-time data, cache aggressively, and build proper error handling from day one rather than bolting it on after your first production incident.
If you're building signal-driven strategies, integrating MEXC with a real-time signal platform like VoiceOfChain lets you receive structured trade signals and execute them via the order API without manual intervention. The combination of a solid signal source and reliable API execution is what separates systematic traders from those refreshing charts and clicking buttons. Start with paper trading on testnet if available, validate your execution logic thoroughly, and only move to live capital once your error rates are near zero under normal market conditions.