Skip to main content
Glama

MCP-Pionex

CI Listed on Glama Python 3.11+ MCP SDK 2.x License: MIT

A Model Context Protocol server for the Pionex exchange, built in Python on top of pionex_py, designed around one question: how do you let an LLM touch real money without letting it hallucinate?

It exposes 56 tools — market data, technical analysis, account, spot trading, spot/futures grid bots and Dual Investment — behind a strict safety layer: read-only by default, two-phase commit for every state change, live validation of every symbol and price, operator-set hard limits the model cannot override, idempotency keys, provenance on every response and a local audit trail.

Serves over stdio or Streamable HTTP. Works with Claude Code / Claude Desktop, Cursor, and local LLMs (LM Studio, Ollama via mcphost or the bundled bridge).

🇪🇸 Guía completa en español: docs/GUIA.md · Informe de capacidades: docs/INFORME.md


Why this server

Most exchange MCP servers are thin API wrappers: the model calls new_order and the order goes out. That is fine for a demo and dangerous with a funded account, because language models invent symbols, misremember prices and re-issue calls when a response is slow.

MCP-Pionex treats the model as an untrusted client:

Guardrail

What it means in practice

Read-only by default

Trading, bots, futures and earn writes are off until the operator enables each one by environment variable. The conversation cannot flip them.

Two-phase commit

Every state change is prepare_* → confirm_action. Prepare validates everything against live data and returns a single-use token bound (SHA-256) to the validated parameters, with a TTL. Confirm executes the server-stored parameters — nothing the model passes at confirm time can change them.

Idempotency keys

Every prepared order carries a clientOrderId (server-minted if absent) and returns it. If a confirm response is lost, the model is instructed to reconcile with get_order_by_client_id before re-preparing — never to resubmit blindly.

Live symbol verification

A pair must exist on Pionex right now (GET /common/symbols, 10-min cache). BTCUSDT gets "did you mean BTC_USDT?", not a request.

Hard numeric limits

Per-action notional cap, max LIMIT-price deviation from the live mid-price, max leverage for futures grids, optional symbol whitelist. All operator-set, all enforced server-side.

Closed vocabularies

side, order_type, interval, grid_type, trend, product_type… are validated against whitelists mirroring the Pionex docs; an invalid value returns the full valid list so the model self-corrects.

Provenance envelopes

Every response carries source (endpoint), fetched_at (UTC) and a computed flag separating exchange facts from server-derived values (indicators, mid-price, portfolio weights).

Verbatim errors

Pionex API errors pass through with their original code and message. Never paraphrased.

MCP annotations

All 56 tools declare readOnlyHint / destructiveHint / idempotentHint / openWorldHint, so MCP clients can require human approval on destructive calls.

Audit log

Every prepare, confirm and cancel is appended to a local JSONL file.

Related MCP server: bybit-mcp

Tool catalogue

Group

Tools

Access

Meta (2)

get_server_status, get_safety_rules

always

Market (9)

list_symbols, get_symbol_info, get_price, get_ticker_24h, get_book_ticker, get_depth, get_recent_trades, get_klines, get_klines_history

public

Technical analysis (5)

get_emas, get_indicators (RSI, MACD, ATR, Bollinger, SMA/EMA), detect_fvg, detect_order_blocks, get_market_structure

public · all computed

Account (8)

get_balances, get_portfolio, get_open_orders, get_order, get_order_by_client_id, get_order_history, get_fills, get_fills_by_order

API key

Spot trading (7)

prepare_order, prepare_cancel_all_orders, prepare_cancel_orders, cancel_order, compute_rebalance_plan, prepare_rebalance, confirm_action

TRADING_ENABLED

Bots (14)

reads: list_bot_orders, get_spot_grid, get_futures_grid, get_smart_copy, get_grid_ai_strategy, check_spot_grid_params, check_futures_grid_params · spot grid: prepare_create_spot_grid, prepare_adjust_spot_grid, prepare_invest_in_spot_grid, prepare_extract_spot_grid_profit, prepare_cancel_spot_grid · futures grid: prepare_create_futures_grid, prepare_cancel_futures_grid

reads: API key · spot: BOTS_ENABLED · futures: BOTS_ENABLED + FUTURES_ENABLED

Earn / Dual Investment (11)

list_dual_symbols, list_dual_products, get_dual_prices, get_dual_index, get_dual_delivery_prices, get_dual_balances, query_dual_invests, get_dual_records, prepare_dual_invest, prepare_dual_revoke, prepare_dual_collect

reads: public / API key · writes: EARN_ENABLED

Every tool description follows the same structure — purpose, when to use it versus sibling tools, arguments with ranges, return shape, requirements — so both models and humans can pick the right one. Field-level detail: docs/INFORME.md.

Quick start

Requirements: Python ≥ 3.11, uv (or pip). A Pionex API key is only needed for account/trading tools; market data and technical analysis work without one.

git clone https://github.com/alejandrorodm/MCP-Pionex
cd MCP-Pionex
uv sync

Claude Code

claude mcp add pionex \
  --env PIONEX_API_KEY=your_key \
  --env PIONEX_API_SECRET=your_secret \
  -- uv --directory /absolute/path/to/MCP-Pionex run mcp-pionex

Claude Desktop / Cursor / any MCP client (mcp.json)

{
  "mcpServers": {
    "pionex": {
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/MCP-Pionex", "run", "mcp-pionex"],
      "env": {
        "PIONEX_API_KEY": "your_key",
        "PIONEX_API_SECRET": "your_secret",
        "PIONEX_MCP_TRADING_ENABLED": "false"
      }
    }
  }
}

Remote / multi-client: Streamable HTTP

uv run mcp-pionex --transport streamable-http --host 127.0.0.1 --port 8000
# → http://127.0.0.1:8000/mcp

Same server, same guardrails, served over the MCP Streamable HTTP transport instead of stdio, so several clients (or a client on another machine) can share one process. Keep it on localhost or behind an authenticating reverse proxy: the API credentials live in this process.

Local LLMs

  • LM Studio — native MCP support: paste the same mcpServers block into its mcp.json.

  • Ollama + mcphost — mcphost -m ollama:qwen3 --config mcp.json.

  • Bundled bridge — uv run examples/ollama_bridge.py "what's BTC at?" runs a full agentic loop against Ollama with all 56 tools.

Keep PIONEX_MCP_TRADING_ENABLED=false with small local models unless closely supervised: the server guardrails are identical, but small models hallucinate more.

Configuration

Everything is controlled by environment variables (template in .env.example). Defaults are the most conservative possible.

Variable

Default

Description

PIONEX_API_KEY / PIONEX_API_SECRET

—

API credentials. Server environment only — never in the chat.

PIONEX_MCP_TRADING_ENABLED

false

Enable spot orders, cancels and rebalancing

PIONEX_MCP_BOTS_ENABLED

false

Enable spot grid create / adjust / invest / close

PIONEX_MCP_FUTURES_ENABLED

false

Enable futures (leveraged) grids — requires BOTS_ENABLED too

PIONEX_MCP_EARN_ENABLED

false

Enable Dual Investment invest / revoke / collect

PIONEX_MCP_MAX_ORDER_NOTIONAL

100

Max quote-currency notional per order, investment, margin or rebalance leg

PIONEX_MCP_MAX_PRICE_DEVIATION_PCT

10

Max deviation of a LIMIT price from the live mid-price

PIONEX_MCP_MAX_LEVERAGE

3

Max leverage for futures grids

PIONEX_MCP_SYMBOL_WHITELIST

empty

e.g. BTC_USDT,ETH_USDT to restrict the tradable universe

PIONEX_MCP_CONFIRMATION_TTL

120

Seconds a confirmation token stays valid

PIONEX_MCP_AUDIT_LOG

~/.mcp_pionex/audit.jsonl

Audit trail path

Recommended postures: query only (default, zero risk) → bounded trading (TRADING_ENABLED + low notional + whitelist) → full (all gates, notional at your risk tolerance) → leveraged (add FUTURES_ENABLED with a low MAX_LEVERAGE).

How a trade flows

User:  what's ETH at?
AI  →  get_price("ETH_USDT")                     # live, never from memory

User:  buy 20 USDT of ETH
AI  →  prepare_order(symbol="ETH_USDT", side="BUY", order_type="MARKET", amount="20")
       ← { confirmation_token: "ab12cd34ef56-9f3a",
           client_order_id: "mcp-7c1e9a2b4d60",
           summary: "BUY MARKET on ETH_USDT: spend amount=20 (quote) | est. notional ≈ 20.0000 | ...",
           expires_in_seconds: 120 }
       shows the summary and waits

User:  confirm
AI  →  confirm_action("ab12cd34ef56-9f3a")       # executes the STORED params
       ← { action: "place_order", result: { orderId: 1234567, ... } }

If trading is disabled, prepare_order returns the exact environment variable the operator has to set. If the token is reused, expired, or the notional exceeds the cap, the error says so and tells the model what to do instead. If the confirm response is lost, get_order_by_client_id("mcp-7c1e9a2b4d60") tells you whether the order was placed.

Project layout

src/mcp_pionex/
├── server.py      # MCPServer, anti-hallucination instructions, meta tools
├── config.py      # operator settings from the environment (conservative defaults)
├── safety.py      # vocabularies, live symbol check, two-phase commit, limits,
│                  # idempotency keys, annotations, envelopes, audit
├── client.py      # lazy singletons over pionex_py clients
├── actions.py     # executor registry for confirm_action
├── ta.py          # pure technical-analysis maths (offline-tested)
└── tools/
    ├── market.py    # 9 public market tools
    ├── analysis.py  # 5 technical-analysis tools
    ├── account.py   # 8 read-only account tools
    ├── trading.py   # 7 spot-trading tools (two-phase)
    ├── bots.py      # 14 spot/futures grid + smart-copy tools
    └── earn.py      # 11 Dual Investment tools

Development

uv run --with pytest pytest tests/ -q       # 45 offline tests: safety, annotations, idempotency, TA
uv run python -c "from mcp_pionex.server import mcp; import asyncio; \
  print(len(asyncio.run(mcp.list_tools())), 'tools')"   # → 56 tools

CI runs the suite on Python 3.11 and 3.12 and asserts the tool count. See CHANGELOG.md for release history and CLAUDE.md for the contributor guide (tool pattern, how to add a two-phase action).

Known limits

  • No WebSocket streams (MCP is request/response) — use get_klines / get_price for snapshots.

  • Futures grid adjust / reduce, smart-copy writes, user signals and Earn Arbitrage are not exposed.

  • Pending confirmation tokens live in memory: restarting the server invalidates them (by design).

  • Pionex caps klines at 500 per request (paged up to 5000 here) and order history at 200.

License

MIT — © Alejandro Rodríguez Moreno

Available Tools

43 tools
cancel_orderA

Cancel ONE specific open order by orderId. Direct (no token needed): cancelling a single identified order is low-risk and reversible in effect. The order_id must come from get_open_orders or a prior placement — never from memory.

Inputs: symbol (required), order_id (required).

check_spot_grid_paramsA

Ask the EXCHANGE to validate spot-grid parameters without creating anything. Always run this before prepare_create_spot_grid — the exchange's verdict beats any local reasoning.

Inputs: row (required), top (required), base (required), quote (required), +3 more.

compute_rebalance_planA

Compute (dry-run, nothing executed) the MARKET orders needed to move the portfolio to target weights. target_weights_json is a JSON object like {"BTC": 0.5, "ETH": 0.3, "USDT": 0.2} — fractions summing to ~1.0. threshold: minimum weight drift before an order is generated. Review the plan, then use prepare_rebalance to get a confirmation token.

Inputs: target_weights_json (required), threshold. Returns: result

confirm_actionA

STEP 2 of 2: execute a previously prepared action (order, cancel-all, rebalance, bot or investment) using its single-use token. Only call this after the human user has explicitly approved the summary shown by the prepare_* tool. The parameters executed are the ones stored at prepare time — nothing can be changed here.

Inputs: confirmation_token (required). Returns: result

detect_fvgA

Fair Value Gaps (definición de 3 velas) sobre velas reales: FVG alcista cuando low[i+1] > high[i-1]; bajista cuando high[i+1] < low[i-1]. Cada gap incluye zona [bottom, top], timestamp de formación y estado (open / partially_filled / filled). only_open=True omite los ya rellenados. min_gap_pct filtra huecos menores a ese % del precio. HEURÍSTICA computada, no un hecho del exchange.

Inputs: symbol (required), interval (required), lookback, only_open, +1 more. Returns: result

detect_order_blocksC

Order blocks sobre velas reales, heurística de desplazamiento: una vela con cuerpo > displacement_factor × ATR(14) marca impulso; el order block es la última vela contraria en las 3 previas (zona [low, high]). Estado: fresh / mitigated / broken. HEURÍSTICA computada — otras definiciones de OB darán zonas distintas.

Inputs: symbol (required), interval (required), lookback, only_unmitigated, +1 more. Returns: result

get_balancesB

Account balances per coin: free, frozen and total. Requires API credentials (read permission). Balances are live account facts — never estimate them.

Inputs: include_zero.

get_book_tickerC

Best bid/ask (price and size) for one symbol, or all symbols if symbol is empty.

Inputs: symbol, market_type.

get_depthA

Order book (bids/asks) for a symbol. limit range 1-1000, default 20. Each level is [price, size] as strings, verbatim from the exchange.

Inputs: symbol (required), limit.

get_dual_balancesC

The account's dual-investment balances/positions.

Inputs: no named parameters.

get_dual_indexB

Underlying index price for a dual-investment pair.

Inputs: base (required), quote (required).

get_dual_pricesA

Current prices/yields for specific dual products (comma-separated productIds). The profit value used when investing MUST come from here — a stale or invented profit is rejected by the exchange.

Inputs: base (required), quote (required), product_ids (required).

get_emasB

Valores actuales de EMAs sobre cierres de velas reales. periods: lista separada por comas (p. ej. "20,50,200"). Devuelve por periodo el valor de la EMA, si el precio está por encima, y la distancia en %. DERIVADO de klines vivas — no es un dato del exchange.

Inputs: symbol (required), interval (required), limit, periods. Returns: result

get_fillsA

Recent trade fills (executions) for a symbol — latest 100, with price, size, fee and role (taker/maker).

Inputs: symbol (required), end_time_ms, start_time_ms.

get_fills_by_orderB

All fills belonging to one order — use to compute the real average entry price of a filled order from exchange data.

Inputs: order_id (required).

get_grid_ai_strategyA

Pionex's own AI-recommended grid parameters (top/bottom/row) for a pair. Use these exchange-provided numbers instead of inventing grid bounds.

Inputs: base (required), quote (required).

get_indicatorsB

Panel de indicadores clásicos sobre velas reales: RSI(14), MACD(12,26,9), ATR(14), Bollinger(20,2) y SMA/EMA 20/50/200 — últimos valores. DERIVADO de klines vivas con fórmulas estándar.

Inputs: symbol (required), interval (required), limit. Returns: result

get_klinesA

Candlesticks for a symbol. interval MUST be one of: 1M, 5M, 15M, 30M, 60M, 4H, 8H, 12H, 1D (these exact strings). limit 1-500, default 100. end_time_ms: optional epoch-milliseconds upper bound (0 = now). Times in the response are epoch milliseconds.

Inputs: symbol (required), interval (required), limit, end_time_ms.

get_klines_historyA

Fetch MORE than 500 candles by paging backwards through history. Returns a flat oldest-first list. Use for backtests/long lookbacks; capped at 5000 candles per call.

Inputs: total (required), symbol (required), interval (required), end_time_ms. Returns: result

get_market_structureA

Estructura de mercado sobre velas reales: puntos de giro (fractales de swing_strength velas por lado) etiquetados HH/LH/HL/LL, y lectura de tendencia (uptrend/downtrend/range) de las últimas 4 etiquetas. HEURÍSTICA computada.

Inputs: symbol (required), interval (required), lookback, swing_strength. Returns: result

get_open_ordersC

Currently open (unfilled) spot orders for a symbol.

Inputs: symbol (required).

get_orderB

Details of one order by its numeric orderId: status (OPEN/CLOSED), filled size, average price, fee.

Inputs: order_id (required).

get_order_by_client_idA

Details of one order by the clientOrderId string it was created with.

Inputs: client_order_id (required).

get_order_historyA

Historical orders for a symbol (default 50, max 200). Optional epoch-ms time range.

Inputs: symbol (required), limit, end_time_ms, start_time_ms.

get_portfolioA

Whole-portfolio view valued in the quote currency: per-coin amount, live price, value and weight, sorted by value, plus the total. Prices are fetched live; value and weight are computed from them.

Inputs: quote. Returns: result

get_priceA

Live mid-price ((best bid + best ask) / 2) for a symbol, falling back to last traded price for illiquid pairs. This is the ONLY valid source for a current price — never quote prices from memory.

Inputs: symbol (required), market_type. Returns: result

get_recent_tradesC

Recent public trades for a symbol. limit range 10-500, default 100.

Inputs: symbol (required), limit.

get_safety_rulesA

The full list of anti-hallucination and safety rules this server enforces. Use it to explain to the user why an action was blocked.

Inputs: no named parameters. Returns: result

get_server_statusA

Server status: version, which capability gates (trading/bots/earn) are enabled, active limits, and whether API credentials are configured. Call this first when a session starts or when a tool reports it is disabled.

Inputs: no named parameters. Returns: result

get_spot_gridA

Full state of one spot grid bot by its buOrderId: bounds, rows, investment, profit, status.

Inputs: bu_order_id (required).

get_symbol_infoA

Exchange metadata for one symbol: precision (base/quote/amount), minimum trade size, minimum notional, enabled status. Call this before sizing any order — precision and minimums come from here, never from memory.

Inputs: symbol (required), market_type.

get_ticker_24hB

24-hour rolling stats (open/close/high/low/volume/amount/count) for one symbol, or for every symbol if symbol is empty.

Inputs: symbol, market_type.

list_bot_ordersB

List the account's trading bots. Optional filters: status (e.g. 'RUNNING', 'FINISHED'), base/quote coin, bot_types comma-separated (e.g. 'SPOT_GRID,FUTURES_GRID').

Inputs: base, quote, status, bot_types.

list_dual_productsB

Dual-investment products currently open for subscription. product_type MUST be 'DUAL_BASE' (invest the base coin, e.g. BTC) or 'DUAL_CURRENCY' (invest the quote, e.g. USDT). Yields and strike prices come verbatim from the exchange.

Inputs: base (required), quote (required), product_type (required), currency.

list_dual_symbolsC

Pairs supported by Dual Investment. Note Pionex's quote convention: BTC/ETH pairs use quote 'USDXO' (USDC+USDT bundled); others use 'USDT'.

Inputs: base.

list_symbolsA

List real trading symbols on Pionex, exactly as the exchange spells them (format BASE_QUOTE, e.g. 'BTC_USDT'). market_type: 'SPOT' or 'PERP'. Optional case-insensitive search substring filter. Use this instead of guessing symbol names.

Inputs: search, market_type.

prepare_cancel_all_ordersA

STEP 1 of 2 to cancel EVERY open order on a symbol. Returns a confirmation token; nothing is cancelled until confirm_action.

Inputs: symbol (required).

prepare_cancel_spot_gridB

STEP 1 of 2 to close a running spot grid bot. Fetches the bot's live state for the summary and returns a confirmation token.

Inputs: bu_order_id (required).

prepare_create_spot_gridA

STEP 1 of 2 to create a spot grid bot. Validates locally (bounds, row 2-200, grid_type whitelist, notional cap) AND against the exchange's checkParams endpoint, then returns a confirmation token. Nothing is created until confirm_action with that token.

Inputs: row (required), top (required), base (required), quote (required), +3 more.

prepare_dual_investA

STEP 1 of 2 to subscribe to a dual-investment product. Provide EXACTLY ONE of base_amount or currency_amount. profit must be the live value from get_dual_prices. Returns a confirmation token.

Inputs: base (required), profit (required), product_id (required), base_amount, +2 more.

prepare_dual_revokeC

STEP 1 of 2 to revoke an unsettled dual investment. Returns a confirmation token.

Inputs: base (required), product_id (required), client_dual_id (required).

prepare_orderA

STEP 1 of 2 to place a spot order. Validates everything against live exchange data and returns a confirmation token — NO order is sent.

Parameters (all numeric values as strings, exactly as they should reach the exchange):

  • side: 'BUY' or 'SELL'. order_type: 'LIMIT' or 'MARKET'.

  • LIMIT: requires price + size (base units).

  • MARKET BUY: requires amount (quote currency to spend, e.g. USDT).

  • MARKET SELL: requires size (base units to sell).

After this returns, show the summary to the user and only call confirm_action with the token once they explicitly approve.

Inputs: side (required), symbol (required), order_type (required), ioc, +4 more. Returns: result

prepare_rebalanceC

STEP 1 of 2 to EXECUTE a portfolio rebalance as MARKET orders. Recomputes the plan from live data, checks every order against the notional cap, and returns a confirmation token plus the exact plan that will run. Show the plan to the user before confirming.

Inputs: target_weights_json (required), threshold.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 43 tools

    Disambiguation5/5

    Every tool has a clearly distinct purpose: market data, technical indicators, trading, dual investment, and bot management are all separated. Even similar tools like get_klines and get_klines_history are easily distinguishable by their limits and use cases, with no ambiguity between them.

    Naming Consistency5/5

    All 43 tools follow a consistent snake_case verb_noun pattern (get_, list_, prepare_, confirm_, cancel_, compute_, detect_, check_). The naming convention is uniform and predictable, making it easy for an agent to infer function from name.

    Tool Count2/5

    With 43 tools, the server exceeds the 25+ threshold for 'too many'. Although the broad scope (market data, indicators, trading, bots, dual products) justifies a large surface, the sheer number will likely overwhelm agents and increase selection overhead. This is well beyond the typical well-scoped 3-15 tool range.

    Completeness5/5

    The tool surface is comprehensive: it covers market data, technical analysis, order placement/cancellation, portfolio rebalancing, grid bot lifecycle, dual investment subscription/revoke, and account balances. The prepare/confirm pattern for risky actions is well-implemented, and there are no obvious dead ends or missing critical operations.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI tools to execute trades and fetch market data across six crypto exchanges via natural language or API, with dual Telegram and MCP interfaces.
      2
      -
    • A
      license
      B
      quality
      C
      maintenance
      Provides a set of MCP tools to interact with the Bybit cryptocurrency exchange API, enabling market data queries, account management, trading operations, and futures grid strategy analysis via natural language.
      19
      37 npm
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI assistants to interact with the PocketOption trading platform via MCP, including balance checks, candle data, asset screening, and trade placement, with support for multi-agent coordination.
      24
      8
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Provides AI agents with access to Gate.io's cryptocurrency exchange for market data, trading, and account management, plus DEX, news, and research tools via multiple MCP endpoints.
      45
      MIT