Phemex Trading
Trade on Phemex via the phemex-cli tool. Supports USDT-M futures, Coin-M futures, and Spot markets.
What's New in v2.0.0
Standalone CLI release — phemex-cli is now a standalone package (previously bundled with phemex-trade-mcp). Leaner install, no MCP dependencies.
- 1. WebSocket streaming —
phemex-cli subscribe ticker|trade|orderbook --symbol SYMBOL for real-time market data. list_symbols tool — Discover all available trading pairs, filtered by contract type.- Config file (
~/.phemexrc) — Store API credentials persistently. No need to export env vars every session. --help for every tool — Run phemex-cli <tool> --help to see parameters, defaults, and usage examples inline.- Friendly field names — API field suffixes (
closeRp, fundingRateRr) are mapped to readable names (closePrice, fundingRate). Use --raw to get the original names. - Enhanced error messages — Errors now include
suggestion and tip fields with actionable guidance instead of raw API codes.
Before you start
Ensure you have the latest version installed:
CODEBLOCK0
How to call tools
CODEBLOCK1
Or with JSON args:
CODEBLOCK2
Output is always JSON. Credentials are loaded from environment variables or ~/.phemexrc (see Setup).
Tool help
Every tool supports --help with full parameter docs and examples:
CODEBLOCK3
Output:
CODEBLOCK4
More help examples:
CODEBLOCK5
Friendly field names
By default, output uses readable field names:
CODEBLOCK6
CODEBLOCK7
Use --raw to get original API field names (for scripts that depend on old format):
CODEBLOCK8
CODEBLOCK9
Field name mapping reference:
| Suffix | Meaning | Example | Mapped to |
|---|
| INLINECODE18 | Real Price | INLINECODE19 | INLINECODE20 |
| INLINECODE21 |
Real Value |
accountBalanceRv |
accountBalance |
|
Rr | Real Rate |
fundingRateRr |
fundingRate |
|
Rq | Real Quantity |
volumeRq |
volume |
Contract types
Every tool accepts an optional --contractType flag:
- -
linear (default) — USDT-M perpetual futures. Symbols end in USDT (e.g. BTCUSDT). - INLINECODE32 — Coin-M perpetual futures. Symbols end in USD (e.g. BTCUSD).
- INLINECODE33 — Spot trading. Symbols end in USDT (e.g. BTCUSDT). The CLI auto-prefixes
s for the API.
Tools
Market data (no auth needed)
- -
get_ticker — 24hr price ticker. Example: INLINECODE36 - INLINECODE37 — Order book (30 levels). Example: INLINECODE38
- INLINECODE39 — Candlestick data. Example: INLINECODE40
- INLINECODE41 — Recent trades. Example: INLINECODE42
- INLINECODE43 — Funding rate history. Example: INLINECODE44
Account (read-only, auth required)
- -
get_account — Balance and margin info. Example: INLINECODE46 - INLINECODE47 — Spot wallet balances. Example: INLINECODE48
- INLINECODE49 — Current positions with PnL. Example: INLINECODE50
- INLINECODE51 — Open orders. Example: INLINECODE52
- INLINECODE53 — Closed/filled orders. Example: INLINECODE54
- INLINECODE55 — Trade execution history. Example: INLINECODE56
Trading (auth required)
- -
place_order — Place an order (Market, Limit, Stop, StopLimit). Key params: --symbol, --side (Buy/Sell), --orderQty, --ordType, --price (Limit/StopLimit), --stopPx (Stop/StopLimit), --timeInForce (GoodTillCancel/PostOnly/ImmediateOrCancel/FillOrKill), --reduceOnly, --posSide (Long/Short/Merged), --stopLoss, --takeProfit, --qtyType (spot only). orderQty units differ by contract type:
-
linear (USDT-M): orderQty = base currency amount (e.g.
0.01 = 0.01 BTC). To buy 10 USDT worth, calculate qty = 10 / current price.
-
inverse (Coin-M): orderQty = number of contracts as integer (e.g.
10 = 10 contracts). Each contract has a fixed USD value (e.g. 1 USD/contract for BTCUSD).
-
spot: depends on
--qtyType.
ByBase (default) = base currency (e.g.
0.01 = 0.01 BTC).
ByQuote = quote currency (e.g.
50 = 50 USDT worth of BTC).
- Example:
phemex-cli place_order --symbol BTCUSDT --side Buy --orderQty 0.01 --ordType Market
- -
amend_order — Modify an open order. Example: INLINECODE82 - INLINECODE83 — Cancel one order. Example: INLINECODE84
- INLINECODE85 — Cancel all orders for a symbol. Example: INLINECODE86
- INLINECODE87 — Set leverage. Example: INLINECODE88
- INLINECODE89 — Switch OneWay/Hedged. Example: INLINECODE90
Transfers (auth required)
- -
transfer_funds — Move funds between spot and futures. Example: INLINECODE92 - INLINECODE93 — Transfer history. Example: INLINECODE94
Utility
- -
list_symbols — List all available trading symbols, grouped by contract type.
CODEBLOCK10
Example output:
CODEBLOCK11
Use list_symbols to discover valid symbol names before trading. This avoids "invalid symbol" errors.
Streaming (WebSocket, no auth needed)
Subscribe to real-time market data streams. Output is JSON to stdout, logs to stderr.
CODEBLOCK12
Features: auto-reconnect with exponential backoff, Ctrl+C for graceful shutdown.
Error messages
Errors return structured JSON with actionable guidance. Examples:
Invalid symbol:
CODEBLOCK13
CODEBLOCK14
Common typo (BTCUSD instead of BTCUSDT):
CODEBLOCK15
CODEBLOCK16
Order quantity too large:
CODEBLOCK17
Other enhanced errors: insufficient balance, invalid API key, rate limiting, invalid leverage, order not found — all include suggestion and tip fields.
Safety rules
- 1. Always confirm before placing orders. Before calling
place_order, show the user exactly what the order will do: symbol, side, quantity, type, price. Ask for confirmation. - Always confirm before cancelling all orders. Before calling
cancel_all_orders, list the open orders first and confirm with the user. - Explain leverage changes. Before calling
set_leverage, explain the implications (higher leverage = higher liquidation risk). - Show context before trading. Before suggesting a trade, show current positions and account balance so the user can make an informed decision.
- Never auto-trade. Do not place orders without explicit user instruction.
Common workflows
Check a price
CODEBLOCK18
Discover available symbols
CODEBLOCK19
Place a market buy (USDT-M futures)
CODEBLOCK20
Place a limit sell (Coin-M futures)
CODEBLOCK21
Buy spot
CODEBLOCK22
Check positions
CODEBLOCK23
Stream real-time prices
CODEBLOCK24
Get help for any command
CODEBLOCK25
Setup
Option 1: Config file (recommended)
Create ~/.phemexrc — credentials persist across sessions without exporting env vars:
CODEBLOCK26
That's it. All phemex-cli commands will pick up these values automatically.
Option 2: Environment variables
CODEBLOCK27
Configuration priority
Settings are loaded in this order (highest priority first):
- 1. Command-line arguments
- Environment variables
- INLINECODE104 config file
- Defaults (testnet URL)
This means env vars always override the config file, so you can safely keep production creds in ~/.phemexrc and temporarily override with PHEMEX_API_URL=https://testnet-api.phemex.com phemex-cli ... for testing.
Steps
- 1. Create a Phemex account at https://phemex.com
- Create an API key (Account → API Management)
- Save credentials to
~/.phemexrc or export as environment variables - Verify:
phemex-cli list_symbols --contractType linear should return symbols - Optionally set
PHEMEX_API_URL (defaults to testnet https://testnet-api.phemex.com for safety; set to https://api.phemex.com for real trading) - Optionally set
PHEMEX_MAX_ORDER_VALUE to limit maximum order size (USD)
Phemex 交易
通过 phemex-cli 工具在 Phemex 上进行交易。支持 USDT-M 合约、Coin-M 合约和现货市场。
v2.0.0 新特性
独立 CLI 版本发布 — phemex-cli 现为独立包(此前与 phemex-trade-mcp 捆绑)。安装更精简,无 MCP 依赖。
- 1. WebSocket 流 — phemex-cli subscribe ticker|trade|orderbook --symbol SYMBOL 获取实时市场数据。
- list_symbols 工具 — 发现所有可用交易对,可按合约类型筛选。
- 配置文件 (~/.phemexrc) — 持久化存储 API 凭证。无需每次会话都 export 环境变量。
- 每个工具都支持 --help — 运行 phemex-cli --help 查看参数、默认值和内联使用示例。
- 友好的字段名称 — API 字段后缀(closeRp、fundingRateRr)映射为可读名称(closePrice、fundingRate)。使用 --raw 获取原始名称。
- 增强的错误消息 — 错误现在包含 suggestion 和 tip 字段,提供可操作指导,而非原始 API 代码。
开始之前
确保已安装最新版本:
bash
npm install -g phemex-cli@latest
如何调用工具
bash
phemex-cli --param1 value1 --param2 value2
或使用 JSON 参数:
bash
phemex-cli {param1:value1,param2:value2}
输出始终为 JSON。凭证从环境变量或 ~/.phemexrc 加载(参见设置)。
工具帮助
每个工具都支持 --help,包含完整参数文档和示例:
bash
phemex-cli place_order --help
输出:
用法: phemex-cli place_order [选项]
下单(市价、限价、止损、止损限价)
必需参数:
--symbol 交易对(例如 BTCUSDT)
--side 买入或卖出
--orderQty 数量。线性:基础货币数量(0.01 = 0.01 BTC)。...
--ordType 订单类型:Market、Limit、Stop、StopLimit
可选参数:
--price 限价(Limit/StopLimit 必需)
--timeInForce GoodTillCancel、PostOnly... [默认: GoodTillCancel]
--reduceOnly 仅减仓 [默认: false]
...
示例:
phemex-cli place_order --symbol BTCUSDT --side Buy --orderQty 0.01 --ordType Market
phemex-cli place_order --symbol BTCUSDT --side Sell --orderQty 0.01 --ordType Limit --price 90000 --timeInForce PostOnly
更多帮助示例:
bash
phemex-cli get_ticker --help # 查看价格行情参数
phemex-cli get_klines --help # 查看K线分辨率值
phemex-cli set_leverage --help # 查看杠杆参数格式
phemex-cli transfer_funds --help # 查看转账方向值
phemex-cli list_symbols --help # 查看合约类型筛选
友好的字段名称
默认情况下,输出使用可读字段名称:
bash
phemex-cli get_ticker --symbol BTCUSDT
json
{
closePrice: 70549.9,
openPrice: 70192.7,
highPrice: 70750,
lowPrice: 69160,
markPrice: 70549.9,
fundingRate: -0.00003417,
volume: 5303.525,
turnover: 371204351.5978
}
使用 --raw 获取原始 API 字段名称(适用于依赖旧格式的脚本):
bash
phemex-cli get_ticker --symbol BTCUSDT --raw
json
{
closeRp: 70549.9,
openRp: 70192.7,
highRp: 70750,
lowRp: 69160,
markPriceRp: 70549.9,
fundingRateRr: -0.00003417,
volumeRq: 5303.525,
turnoverRv: 371204351.5978
}
字段名称映射参考:
| 后缀 | 含义 | 示例 | 映射为 |
|---|
| Rp | 实际价格 | closeRp | closePrice |
| Rv |
实际价值 | accountBalanceRv | accountBalance |
| Rr | 实际费率 | fundingRateRr | fundingRate |
| Rq | 实际数量 | volumeRq | volume |
合约类型
每个工具都接受可选的 --contractType 标志:
- - linear(默认)— USDT-M 永续合约。交易对以 USDT 结尾(例如 BTCUSDT)。
- inverse — Coin-M 永续合约。交易对以 USD 结尾(例如 BTCUSD)。
- spot — 现货交易。交易对以 USDT 结尾(例如 BTCUSDT)。CLI 会自动为 API 添加 s 前缀。
工具
市场数据(无需认证)
- - getticker — 24小时价格行情。示例:phemex-cli getticker --symbol BTCUSDT
- getorderbook — 订单簿(30档)。示例:phemex-cli getorderbook --symbol BTCUSDT
- getklines — K线数据。示例:phemex-cli getklines --symbol BTCUSDT --resolution 3600 --limit 100
- getrecenttrades — 近期成交。示例:phemex-cli getrecenttrades --symbol BTCUSDT
- getfundingrate — 资金费率历史。示例:phemex-cli getfundingrate --symbol .BTCFR8H --limit 20
账户(只读,需认证)
- - getaccount — 余额和保证金信息。示例:phemex-cli getaccount --currency USDT
- getspotwallet — 现货钱包余额。示例:phemex-cli getspotwallet
- getpositions — 当前持仓及盈亏。示例:phemex-cli getpositions --currency USDT
- getopenorders — 未成交订单。示例:phemex-cli getopenorders --symbol BTCUSDT
- getorderhistory — 已关闭/已成交订单。示例:phemex-cli getorderhistory --symbol BTCUSDT --limit 50
- gettrades — 成交历史。示例:phemex-cli gettrades --symbol BTCUSDT --limit 50
交易(需认证)
- - place_order — 下单(市价、限价、止损、止损限价)。关键参数:--symbol、--side(Buy/Sell)、--orderQty、--ordType、--price(Limit/StopLimit)、--stopPx(Stop/StopLimit)、--timeInForce(GoodTillCancel/PostOnly/ImmediateOrCancel/FillOrKill)、--reduceOnly、--posSide(Long/Short/Merged)、--stopLoss、--takeProfit、--qtyType(仅现货)。orderQty 单位因合约类型而异:
- linear(USDT-M):orderQty = 基础货币数量(例如 0.01 = 0.01 BTC)。要购买价值 10 USDT,计算 qty = 10 / 当前价格。
- inverse(Coin-M):orderQty = 合约数量(整数,例如 10 = 10 张合约)。每张合约有固定美元价值(例如 BTCUSD 为 1 USD/合约)。
- spot:取决于 --qtyType。ByBase(默认)= 基础货币(例如 0.01 = 0.01 BTC)。ByQuote = 报价货币(例如 50 = 价值 50 USDT 的 BTC)。
- 示例:phemex-cli place_order --symbol BTCUSDT