phemex-trade-mcp
v1.2.0
Published
MCP server for trading on Phemex — USDT-M futures, Coin-M futures, and Spot markets
Maintainers
Readme
phemex-trade-mcp
MCP server for trading on Phemex — supports USDT-M futures, Coin-M futures, and Spot markets.
Built on the Model Context Protocol, this server lets AI agents (Claude Desktop, Claude Code, or any MCP client) place orders, manage positions, check balances, and query market data on Phemex.
Available Tools
Market Data (public, no API key required)
| Tool | Description |
|---|---|
| get_ticker | 24hr price ticker for a symbol |
| get_orderbook | Order book snapshot (30 levels) |
| get_klines | Historical candlestick/kline data |
| get_recent_trades | Recent market trades |
| get_funding_rate | Funding rate history (futures only) |
Account (read-only)
| Tool | Description |
|---|---|
| get_account | Futures account balance and margin info |
| get_spot_wallet | Spot wallet balances per currency |
| get_positions | Current positions with unrealized PnL (futures only) |
| get_open_orders | All open orders for a symbol |
| get_order_history | Closed/filled order history |
| get_trades | Trade execution history |
Trading (write)
| Tool | Description |
|---|---|
| place_order | Place an order (Market, Limit, Stop, StopLimit) |
| amend_order | Modify price or quantity of an open order |
| cancel_order | Cancel a single order by orderID or clOrdID |
| cancel_all_orders | Cancel all open orders for a symbol |
| set_leverage | Set leverage for a perpetual symbol (futures only) |
| switch_pos_mode | Switch between OneWay and Hedged mode (USDT-M only) |
Transfers
| Tool | Description |
|---|---|
| transfer_funds | Transfer funds between spot and futures wallets |
| get_transfer_history | Query transfer history |
Utility
| Tool | Description |
|---|---|
| list_symbols | List all available trading symbols, grouped by contract type |
Contract Types
Every tool accepts an optional contractType parameter:
linear(default) — USDT-M perpetual futures. Symbols end inUSDT(e.g.BTCUSDT).inverse— Coin-M perpetual futures. Symbols end inUSD(e.g.BTCUSD).spot— Spot trading. Symbols end inUSDT(e.g.BTCUSDT). The server automatically prependssfor the API.
Setup
1. Get Phemex API credentials
Create an API key at phemex.com (or testnet.phemex.com for testing).
2. Configure environment
Option A: Environment variables — copy .env.example to .env and fill in your keys:
PHEMEX_API_KEY=your-api-key
PHEMEX_API_SECRET=your-api-secret
PHEMEX_API_URL=https://testnet-api.phemex.com
PHEMEX_MAX_ORDER_VALUE=Option B: Config file — create ~/.phemexrc:
# Phemex API Credentials
PHEMEX_API_KEY=your-api-key
PHEMEX_API_SECRET=your-api-secret
PHEMEX_API_URL=https://api.phemex.com
# Optional: max order value limit (USD)
PHEMEX_MAX_ORDER_VALUE=1000Priority (highest to lowest): CLI params → environment variables → ~/.phemexrc → defaults (testnet).
| Variable | Description |
|---|---|
| PHEMEX_API_KEY | Your Phemex API key |
| PHEMEX_API_SECRET | Your Phemex API secret |
| PHEMEX_API_URL | API base URL. Use https://testnet-api.phemex.com for testnet or https://api.phemex.com for production |
| PHEMEX_MAX_ORDER_VALUE | Optional safety limit — max notional order value (USD). Orders exceeding this are rejected client-side |
3. Build
npm install
npm run buildMCP Client Configuration
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"phemex": {
"command": "node",
"args": ["/absolute/path/to/phemex-trade-mcp/dist/index.js"],
"env": {
"PHEMEX_API_KEY": "your-key",
"PHEMEX_API_SECRET": "your-secret",
"PHEMEX_API_URL": "https://testnet-api.phemex.com"
}
}
}
}Claude Code
Add to ~/.claude.json (global) or .mcp.json (per-project):
{
"mcpServers": {
"phemex": {
"command": "node",
"args": ["/absolute/path/to/phemex-trade-mcp/dist/index.js"],
"env": {
"PHEMEX_API_KEY": "your-key",
"PHEMEX_API_SECRET": "your-secret",
"PHEMEX_API_URL": "https://testnet-api.phemex.com"
}
}
}
}OpenClaw
Install the skill from ClawHub:
clawhub install phemex-tradeOr manually copy the skill/phemex-trade/ directory to ~/.openclaw/skills/.
Set your API keys as environment variables:
export PHEMEX_API_KEY=your-key
export PHEMEX_API_SECRET=your-secret
export PHEMEX_API_URL=https://api.phemex.comThe skill uses phemex-cli (included in the npm package) for direct tool invocation — no mcporter needed.
Then ask your OpenClaw agent: "What's the current BTC price on Phemex?"
Any MCP Client (stdio)
This server uses the stdio transport. Launch it as a subprocess and communicate via stdin/stdout:
PHEMEX_API_KEY=... PHEMEX_API_SECRET=... node dist/index.jsUsage Examples
Once connected, ask your AI agent things like:
- "What's the current BTC price on Phemex?"
- "Show me my USDT-M account balance"
- "Place a limit buy for 0.01 BTC at $95,000"
- "What are my open positions?"
- "Cancel all open orders for ETHUSDT"
- "Show the BTCUSD Coin-M order book" (uses
contractType: "inverse") - "Buy 10 USDT worth of BTC on spot" (uses
contractType: "spot",qtyType: "ByQuote") - "Transfer 100 USDT from spot to futures"
Development
npm run dev # watch mode — recompiles on file changes
npm run build # one-time build
npm run test # run tests
npm run start # run the serverArchitecture
src/
index.ts # MCP server entry point — registers all tools
cli.ts # CLI entry point — dispatches to tool handlers
cli-parser.ts # CLI argument parser (flag + JSON modes)
client.ts # Phemex API client (auth, signing, HTTP)
config.ts # Config loading (~/.phemexrc + env vars)
contract-router.ts # Routes tools to correct API endpoints per contract type
errors.ts # Enhanced error messages with suggestions
product-info.ts # Caches product metadata for price/qty scaling
tool-schemas.ts # Tool parameter schemas and --help formatter
types.ts # Shared types
formatters/
field-mapper.ts # Maps API field names to friendly names (--raw to skip)
tools/
get-ticker.ts # One file per MCP tool
list-symbols.ts # List all available trading symbols
place-order.ts
...Key design decisions:
- Contract router — a single
contractTypeparameter on every tool dispatches to the correct Phemex API endpoint (USDT-M/g-*, Coin-M/orders/*, Spot/spot/*). - Automatic scaling — Coin-M and Spot APIs use integer-scaled values (
priceEp,baseQtyEv). The server handles conversion automatically viaProductInfoCache, so agents always work with human-readable decimals. - Symbol resolution — Spot symbols are auto-prefixed with
sfor the API (e.g.BTCUSDTbecomessBTCUSDT). Agents don't need to know this. - Field name mapping — API field suffixes (
closeRp,fundingRateRr, etc.) are mapped to friendly names (closePrice,fundingRate). Use--rawto preserve original names. - Config file —
~/.phemexrcprovides persistent API credentials without exporting env vars every session. - Enhanced errors — Error codes are mapped to human-readable messages with actionable suggestions.
CLI Usage
The package also includes a phemex-cli binary for direct command-line access (used by OpenClaw skills):
# Install globally
npm install -g phemex-trade-mcp
# Set your API keys
export PHEMEX_API_KEY=your-key
export PHEMEX_API_SECRET=your-secret
export PHEMEX_API_URL=https://api.phemex.com
# Use any tool
phemex-cli get_ticker --symbol BTCUSDT
phemex-cli get_positions --currency USDT
phemex-cli place_order --symbol BTCUSDT --side Buy --orderQty 0.01 --ordType Market
# List available symbols
phemex-cli list_symbols
phemex-cli list_symbols --contractType linear
# JSON args also supported
phemex-cli get_ticker '{"symbol":"BTCUSDT"}'
# Help
phemex-cli --help
phemex-cli place_order --help
# Raw output (preserve original API field names)
phemex-cli get_ticker --symbol BTCUSDT --rawWebSocket Streaming
Subscribe to real-time market data streams:
# Subscribe to price ticker (market24h)
phemex-cli subscribe ticker --symbol BTCUSDT
# Subscribe to live trades
phemex-cli subscribe trade --symbol SOLUSDT
# Subscribe to order book updates
phemex-cli subscribe orderbook --symbol ETHUSDTOutput format:
- JSON to stdout (for parsing/piping)
- Logs to stderr (connection status, errors)
Features:
- Auto-reconnect with exponential backoff (1s → 30s)
- Supports SIGINT (Ctrl+C) for graceful shutdown
- WebSocket URL:
wss://ws.phemex.com(configurable viaPHEMEX_WS_URL)
License
ISC
