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

phemex-trade-mcp

v1.2.0

Published

MCP server for trading on Phemex — USDT-M futures, Coin-M futures, and Spot markets

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 in USDT (e.g. BTCUSDT).
  • inverse — Coin-M perpetual futures. Symbols end in USD (e.g. BTCUSD).
  • spot — Spot trading. Symbols end in USDT (e.g. BTCUSDT). The server automatically prepends s for 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=1000

Priority (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 build

MCP 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-trade

Or 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.com

The 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.js

Usage 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 server

Architecture

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 contractType parameter 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 via ProductInfoCache, so agents always work with human-readable decimals.
  • Symbol resolution — Spot symbols are auto-prefixed with s for the API (e.g. BTCUSDT becomes sBTCUSDT). Agents don't need to know this.
  • Field name mapping — API field suffixes (closeRp, fundingRateRr, etc.) are mapped to friendly names (closePrice, fundingRate). Use --raw to preserve original names.
  • Config file~/.phemexrc provides 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 --raw

WebSocket 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 ETHUSDT

Output 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 via PHEMEX_WS_URL)

License

ISC