perp-cli
perp-cli
CLI для торговли бессрочными фьючерсами на нескольких DEX — Pacifica (Solana), Hyperliquid (HyperEVM), Lighter (Ethereum), Aster (BNB Chain).
npm install -g perp-cli # global install
perp --json portfolio
# Or without global install (restricted environments)
npx -y perp-cli --json portfolioФункции
4 биржи — торговля, мосты, арбитраж между Pacifica, Hyperliquid, Lighter, Aster
Арбитраж ставок финансирования (Funding Rate Arb) — сканирование perp-perp + spot-perp и исполнение обеих сторон одной командой
Портфель — один вызов возвращает балансы, позиции и уровень риска по всем биржам
Средства — ввод, вывод, перевод, мосты между сетями (cctp/relay/debridge), ребалансировка между биржами — всё в одной группе
Боты — TWAP, сетка (grid), DCA, трейлинг-стоп с управлением фоновыми задачами
Agent-First дизайн —
--json,--fields,--ndjson,--dry-run, интроспекция схемы во время выполненияБезопасность — проверка перед сделкой, очистка ответов, дедупликация client-id
Related MCP server: dex-kline-mcp
Настройка
# Set exchange keys
perp wallet set pac <SOLANA_KEY> # Pacifica
perp wallet set hl <EVM_KEY> # Hyperliquid
perp wallet set lt <EVM_KEY> # Lighter (API key auto-generated)
perp wallet set aster <API_KEY> # Aster (BNB Chain)
# Or interactive setup wizard
perp setup
# Verify
perp wallet showОдин и тот же EVM-ключ работает как для Hyperliquid, так и для Lighter.
Индекс API-ключа Lighter: Индексы 0–3 зарезервированы фронтендом Lighter (веб/мобильный). perp-cli по умолчанию использует индекс
4. Переопределите его с помощью переменной окруженияLIGHTER_API_KEY_INDEXили используйтеperp wallet agent approve lighter --api-key-index <n>для слотов управляемых агентов. Допустимый диапазон: 4–254.
Группы команд
Группа | Описание |
| Цены, стакан, ставки финансирования, графики, DEX HIP-3 |
| Баланс, позиции, ордера, маржа |
| Рыночные/лимитные/стоп-ордера, закрытие, масштабирование, раздельное исполнение |
| Арбитраж ставок финансирования — сканирование, исполнение, закрытие, мониторинг (perp-perp и spot-perp) |
| 19 алгоритмов ботов (grid, dca, twap, APEX, REFLECT, пресеты) + вложенные скриптовые планы |
| Ввод, вывод, перевод, кроссчейн-мосты (несколько провайдеров), ребалансировка между биржами |
| Лимиты риска, дистанция до ликвидации, защитные механизмы |
| Управление несколькими кошельками и ончейн-балансами |
| Журнал исполнения, PnL, анализ эффективности |
| Режим маржи, субсчета, API-ключи, конструктор |
| Единый обзор по всем биржам |
| Веб-дашборд в реальном времени |
| Настройки CLI (рефералы, значения по умолчанию) |
| Бэктестинг стратегий |
| Супервизор фоновых процессов (сессии tmux для стратегий, алертов и т.д.) |
| Telegram-алерты по ставкам финансирования с фоновым демоном |
| Интроспекция схемы, возможности, проверка состояния |
| Интерактивный мастер настройки (алиас: |
| Единый дашборд: балансы, позиции, арбитражные возможности |
Основные команды
# Portfolio (balances + positions + risk across all exchanges)
perp --json portfolio
# Market data
perp --json -e <EX> market list
perp --json -e <EX> market book <SYM>
perp --json -e <EX> market mid <SYM> # fast mid-price lookup
perp --json -e <EX> market funding <SYM>
perp --json -e <EX> market kline <SYM> 1h # candlestick data
perp --json -e hl market hip3 # list HIP-3 deployed dexes
# Trading
perp --json -e <EX> trade buy <SYM> <SIZE> # shortcut for market buy
perp --json -e <EX> trade sell <SYM> <SIZE> # shortcut for market sell
perp --json -e <EX> trade market <SYM> buy <SIZE> --smart # IOC limit (less slippage)
perp --json -e <EX> trade split <SYM> buy 5000 # orderbook-aware split (large orders)
perp --json -e <EX> trade close <SYM>
perp --json -e <EX> trade flatten # close ALL positions on exchange
perp --json -e <EX> trade reduce <SYM> 50 # reduce position by 50%
perp --json -e <EX> trade cancel <SYM> # cancel by symbol (or orderId)
perp --json -e <EX> trade tpsl <SYM> long # set take-profit / stop-loss
perp --json -e <EX> trade leverage <SYM> <N>
# Account
perp --json -e <EX> account balance
perp --json -e <EX> account positions
perp --json -e <EX> account pnl # realized + unrealized + funding
perp --json -e <EX> account funding # personal funding payment history
perp --json -e <EX> account settings # per-market leverage & margin mode
# Funding rate arbitrage
perp --json arb scan --min 5 # perp-perp opportunities
perp --json arb scan --mode spot-perp # spot+perp opportunities
perp --json arb scan --rates # funding rates across all exchanges
perp --json arb scan --basis # cross-exchange basis opportunities
perp --json arb scan --gaps # cross-exchange price gaps
perp --json arb scan --hip3 # HIP-3 cross-dex funding spreads
perp --json arb scan --live # continuous live monitoring
perp --json arb exec <SYM> <longEx> <shortEx> <$> # perp-perp dual-leg entry
perp --json arb exec <SYM> spot:<exch> <perpEx> <$> # spot+perp entry
perp --json arb config # show arb defaults
perp --json arb history # past arb trade performance (alias: log)
# Funds (deposit, withdraw, transfer, bridge, rebalance)
perp --json funds deposit hyperliquid 100
perp --json funds withdraw pacifica 50
perp --json funds transfer 100 <ADDRESS> # HL internal transfer (instant)
perp --json funds bridge quote --from solana --to arbitrum --amount 100
perp --json funds bridge send --from solana --to arbitrum --amount 100 # auto-cheapest provider
perp --json funds bridge exchange --from pacifica --to hyperliquid --amount 100
perp --json funds rebalance check # balances across exchanges
perp --json funds rebalance plan # compute optimal moves
perp --json funds rebalance execute --auto-bridge # withdraw → bridge → deposit
perp --json funds info # all routes & limits
# Risk
perp --json risk limits --max-leverage 5
perp --json risk liquidation-distance
# Strategies (19 bot algorithms + nested scripted plans)
perp strategy list-strategies # list all available strategies
perp strategy run <strategy> [symbol] # run any strategy
perp strategy apex [symbol] # APEX autonomous orchestrator
perp strategy reflect # trading performance analysis
perp strategy preset-list # list strategy presets
perp --json strategy twap <SYM> buy <SIZE> 30m
perp --json strategy grid <SYM> --range 5 --grids 10 --size 100
perp strategy plan example # scripted multi-step plan format
perp --json strategy plan validate <FILE> # validate scripted plan
perp --json strategy plan execute <FILE> --dry-run # dry-run scripted plan
# Background process supervisor (tmux)
perp background list # list running jobs
perp background stop <ID> # stop a job
perp background logs <ID> -f # follow logs
Telegram-алерты
Алерты по ставкам финансирования через Telegram с поддержкой фонового демона.
# Interactive setup (BotFather token + chat ID auto-detection)
perp alerts setup
# Add alert rules
perp alerts add ETH 30 # alert when ETH funding > 30% annualized
perp alerts add --all 50 # alert for any symbol > 50%
# Test & manage
perp alerts test # send test message
perp alerts list # show active rules
# Run daemon
perp alerts start # foreground
perp alerts start --background # tmux background daemon
perp alerts stop # stop background daemonПроцесс настройки: токен BotFather → проверка бота → отправка /start боту → автоопределение ID чата → тестовое сообщение.
Флаг биржи: -e hyperliquid / -e pacifica / -e lighter / -e aster (алиасы: hl, pac, lt).
Глобальные флаги: --json, --fields <f>, --ndjson, --dry-run, --dex <name> (HIP-3), -w, --wallet <name>.
MCP-сервер
perp-cli включает полнофункциональный MCP-сервер (18 инструментов, 3 ресурса, 2 промпта) для Claude Desktop, Cursor и других MCP-клиентов.
API-ключи не требуются для рыночных данных — изучайте цены, стаканы, ставки финансирования и арбитражные возможности без какой-либо настройки. Добавляйте ключи только тогда, когда хотите торговать.
{
"mcpServers": {
"perp-cli": {
"command": "npx",
"args": ["-y", "-p", "perp-cli", "perp-mcp"]
}
}
}Опционально: добавьте ключи для торговли и данных аккаунта:
{
"env": {
"PACIFICA_PRIVATE_KEY": "your-solana-key",
"HYPERLIQUID_PRIVATE_KEY": "your-evm-key",
"LIGHTER_PRIVATE_KEY": "your-evm-key",
"ASTER_API_KEY": "your-api-key"
}
}Инструменты только для чтения (ключи не нужны): get_markets, get_orderbook, get_funding_rates, get_prices, arb_scan, health_check
Инструменты для аккаунта и торговли (требуются ключи): get_balance, get_positions, portfolio, trade_preview, trade_execute, trade_close, get_funding_analysis, get_pnl_analysis, get_arb_compare
Ресурсы: market://prices, market://funding-rates, perp://schema
Промпты: trading-guide, arb-strategy
Навык AI-агента
Установите как навык для Claude Code, Cursor, Codex, Gemini CLI и т.д.:
# Using npx (recommended)
npx skills add hypurrquant/perp-cli
# Or via Claude Code slash command
/install-skill hypurrquant/perp-cliСм. skills/perp-cli/SKILL.md для полного руководства по агенту.
Дизайн CLI с приоритетом для агентов
Создано в соответствии с принципами CLI для агентов:
# Every command returns structured JSON envelope
perp --json portfolio
# → { "ok": true, "data": {...}, "meta": { "timestamp": "..." } }
# Filter output to specific fields (saves tokens)
perp --json --fields totalEquity,risk portfolio
# Stream large lists as NDJSON (one JSON per line)
perp --json --ndjson -e hl market list
# Pre-validate before executing
perp --json -e hl trade check BTC buy 0.01
perp --json --dry-run -e hl trade market BTC buy 0.01
# Idempotent orders with client ID
perp --json -e hl trade market BTC buy 0.01 --client-id my-unique-idВсе ответы автоматически очищаются (удаляются управляющие символы, блокируются паттерны инъекций промптов).
Ошибки включают флаг retryable — повторяйте запрос только если он true.
Лицензия
MIT
Available Tools
31 toolsarb_scanA
Scan for funding rate arbitrage opportunities across exchanges. Finds symbols with the largest funding rate spreads
Inputs: symbols, minSpread.
explain_commandA
Explain what a perp CLI command does, its parameters, and any risks. Helps the user understand a command before running it
Inputs: command (required).
get_arb_compareA
Compare active arbitrage positions side by side — ROI, funding income, price PnL, and annualized returns for each position
Inputs: period.
get_balanceA
Get account balance (equity, available margin, margin used, unrealized PnL) on an exchange. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: exchange (required).
get_balance_by_addressA
Balances of ANY account by its public address — keyless, read-only (public venue data; nothing is signed, no key is needed). Venues: pacifica (base58 Solana address), hyperliquid (0x address), lighter (0x address), lighter-rh (0x address), risex (0x address); omit exchange to read every one of them (a venue that fails, address format included, is listed in data.errors). data: { balance (equity / available / marginUsed / unrealizedPnl + venue extras; null on Lighter), spot (token balances; null where the venue does not publish them), accounts (Lighter: one row per account of the address; accountIndex narrows), dexes + accountMode (Hyperliquid: HIP-3 dexes with a non-zero account value; a dex that fails is in meta.errors / meta.warnings — unknown, not zero) }. Other venues: CAPABILITY_UNSUPPORTED; a wrong address format: INVALID_PARAMS. Same data as perp [-e <venue>] account balance --address <addr>.
Inputs: address (required), exchange, accountIndex.
get_funding_analysisA
Analyze funding income across exchanges — cumulative totals, annualized rates, and per-arb-position breakdown. Great for tracking funding arb profitability.
Inputs: period, symbol, exchange.
get_funding_ratesA
Compare funding rates across every market-data venue whose funding rate is verified. Returns rates per symbol with spread analysis. includeUnverified also returns venues whose rate is unverified (QFEX; TxFlow — rate not checked against settled payments; Variational — a predicted rate not checked against settled payments; GRVT — indicative rate; Extended — not checked against settled payments), each row tagged fundingVerified / apiStatus — display only, never a basis for trading (mirrors the CLI arb scan --include-unverified).
Inputs: symbols, minSpread, includeUnverified.
get_marketsA
Get all available perpetual futures markets on an exchange, including price, funding rate, volume, and max leverage. Works without API keys (public market data). Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: exchange (required).
get_open_ordersA
Get all open/pending orders on an exchange. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: exchange (required).
get_option_chainA
Option chain for one expiry (Derive): rows per strike with call and put quotes — bid / ask (price + size; null = empty side), mark, index, forward, IV (mark / bid / ask; null = not computable), greeks (delta, gamma, theta, vega, rho), open interest, 24h volume — plus the ATM strike. Decimals are strings. One venue request per expiry. Public read.
Inputs: venue (required), underlying (required), expiry, strikes.
get_option_expiriesA
List the active option expiries of an underlying on an options venue (Derive): per expiry the UTC date (YYYY-MM-DD), expiry ms, strike and instrument counts, soonest first. Public read — no API key needed.
Inputs: venue (required), underlying (required).
get_option_quoteA
Quote one option instrument (Derive name, e.g. ETH-20261225-3500-P): bid / ask (price + size), mark, index, forward, IV, greeks, open interest, 24h stats. Unknown instrument → SYMBOL_NOT_FOUND. Public read.
Inputs: venue (required), instrument (required).
get_orderbookA
Get the order book (bids and asks) for a symbol on an exchange. Works without API keys on every venue with an account API (configured credentials → the account adapter; none → the public endpoint / read-only adapter); market-data-only venues have no orderbook path. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: symbol (required), exchange (required).
get_outcome_bookB
Get the orderbook for one outcome side. Public read — no API key needed.
Inputs: side (required), outcome (required).
get_outcome_marketsA
List active Hyperliquid Outcome markets (HIP-4). Each market has parsed metadata (underlying asset, target price, expiry, period) and per-side info (Yes/No name, encoding, asset id, current mid). Public read — no API key needed.
Inputs: no named parameters.
get_outcome_positionsA
Get the active account's open outcome positions (size, entry notional, mark price, unrealized PnL). Requires a configured Hyperliquid wallet or agent.
Inputs: no named parameters.
get_outcome_viewA
Get a combined view of one outcome market: all sides' books in parallel + underlying mark price gap (vs targetPrice) + time to expiry + per-side implied probability (mid sum). For binary markets, the symmetric structure means Yes bid + No ask ≈ 1.0 — the view exposes both sides in a single round-trip and surfaces directional context (e.g., is BTC currently above the target). Public read.
Inputs: outcome (required), depth.
get_pnl_analysisA
P&L analysis combining trading fees and funding income — shows net profit/loss by exchange with daily breakdown
Inputs: period, exchange.
get_positionsA
Get all open positions on an exchange, including size, entry price, PnL, leverage. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: exchange (required).
get_positions_by_addressA
Open positions of ANY account by its public address — keyless, read-only (public venue data; nothing is signed, no key is needed). Venues: pacifica (base58 Solana address), hyperliquid (0x address), lighter (0x address), lighter-rh (0x address), risex (0x address). Hyperliquid reads the native dex and every HIP-3 dex (rows carry dex: null | ""; a dex that fails is listed in meta.errors / meta.warnings — its rows are missing, not absent); Lighter reads every account of the address (rows carry accountIndex; accountIndex narrows). Other venues: CAPABILITY_UNSUPPORTED; a wrong address format: INVALID_PARAMS. Same rows as perp -e <venue> account positions --address <addr>.
Inputs: address (required), exchange (required), symbol, accountIndex.
get_pricesB
Get cross-exchange prices for symbols. Fetches mark prices from every market-data venue for comparison; a venue appears in a row only when it lists that symbol (e.g. QFEX lists no BTC). Each row's unofficialApiVenues names the venues in it read through an undocumented API (none at present) — like get_markets' venueApi tag.
Inputs: symbols.
health_checkA
Ping every registered venue on the server's network and return connectivity status and latency. Pacifica / Hyperliquid / Lighter / Aster / QFEX: REST ping (status = HTTP status, 0 = no response); every other venue: its public market-data read (status null). A failure carries its error message.
Inputs: no named parameters.
pacifica_print_positionsB
Pacifica Print orders of an account (read-only): current orders, or with history=true every order (paginated: limit / cursor). Status printing | cancelling | filled | liquidated | cancelled | completed | ended.
Inputs: account (required), limit, cursor, history.
pacifica_print_productsA
Pacifica Print products (read-only): game id (e.g. BTC_24H, BTC_7D, BTC_1M), cycle length in days, max leverage, deposit caps, allowed target distance from mark. Print = a strike order that earns a premium each cycle; while resting it fills / is liquidated only at a cycle checkpoint, after a fill it is an ordinary perp position (continuous liquidation).
Inputs: no named parameters.
pacifica_print_quoteA
Validate a Pacifica Print order and preview it (read-only, nothing signed): notional, size on fill, docs-formula liquidation price (an outer bound — a liquidation was observed earlier in one live case; venue trigger unpublished), max loss (deposit + premiums), lock period. The premium is not quoted (the venue's preview is a signed request). Placing the order is CLI-only: perp -e pacifica print deposit … (supports --dry-run).
Inputs: game (required), strike (required), deposit (required), leverage (required), +2 more.
pacifica_vaultsA
Pacifica vaults (API: lakes), read-only. Without vault: every vault (TVL, NAV per share, fee, lock-up, withdrawal window, config); with account: plus that account's shares. With vault (address, or a nickname matching exactly one vault — an ambiguous nickname is INVALID_PARAMS listing the candidates): one vault plus live account equity, positions, deposit whitelist (unofficial endpoint, advisory) and whether withdrawals are open now. APY is not published (null). Deposits / withdrawals are CLI-only: perp -e pacifica vault deposit|withdraw (supports --dry-run).
Inputs: vault, account.
portfolioA
Cross-exchange portfolio summary: balances, positions, and risk metrics across all exchanges with configured credentials
Inputs: no named parameters.
suggest_commandA
Given a natural language trading goal, suggest the exact perp CLI commands to run. Does NOT execute anything — only returns commands for the user to review and run manually
Inputs: goal (required), exchange.
trade_closeA
Close an existing position. IMPORTANT: Call trade_preview first with the opposite side to show impact, then get user confirmation. Verified close: closedSize is the measured / venue-final fill (one residual market close is attempted); a residual still open → ORDER_PARTIAL error (symbol quarantined). Includes the uniform OrderResult of the reduce-only market order. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: symbol (required), exchange (required).
trade_executeA
Execute a REAL trade on the server's network (meta.network; PERP_NETWORK, default mainnet). IMPORTANT: Always call trade_preview first and get explicit user confirmation before calling this tool. Refused with RISK_VIOLATION when the order breaches the local risk limits (perp risk set; there is no override over MCP) or when the symbol is quarantined (only reduce-only orders pass). Every order is written to the execution log. Supports market and limit orders. Returns the uniform OrderResult (status, finality, filledSize, execution: slippage / protection price / TIF sent) with the raw venue response under legacy, plus top-level filledSize / requestedSize / partial. Outcomes: an unknown outcome (transport failure after send, or a non-final venue ack) → ok:false, code ORDER_PENDING, executed:false, pending:true and a "do NOT resubmit" remediation — the symbol is quarantined for opening orders until a human clears it; a final rejection / cancel with nothing filled → ORDER_REJECTED, executed:false; a cancel after a partial fill → executed:true, partial:true with the real filledSize. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: side (required), size (required), symbol (required), exchange (required), +5 more.
trade_previewA
Preview a trade WITHOUT executing. Runs trade_execute's pre-send checks read-only (size parse, order validation incl. TIF, quarantine, local risk limits — never forced) and reports any refusal as valid:false with its code + remediation; also returns the estimated fill price from the book, notional, margin impact, the builder fee the order would carry, and the existing position. Venue trading fees are NOT estimated. ALWAYS call this before trade_execute and show the result to the user for confirmation. Hyperliquid: native perps only (HIP-3 dexes via the CLI --dex).
Inputs: side (required), size (required), symbol (required), exchange (required), +4 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 31 tools
Most tools target distinct resources, but several clusters overlap: get_funding_rates / get_funding_analysis / arb_scan / get_arb_compare all concern funding and arbitrage, and get_positions / get_positions_by_address / get_outcome_positions require careful reading to distinguish. The by-address variants and the outcome view/book/markets trio are also close enough to invite misselection.
All names are snake_case and most use a get_ or trade_ verb prefix, but conventions are mixed: pacifica_print_* and pacifica_vaults use a venue prefix, arb_scan and health_check reverse to noun_verb, and portfolio/suggest_command/explain_command break the pattern. Readable, but not a predictable verb_noun scheme throughout.
31 tools is heavy for a perpetual-futures CLI server and several sit in overlapping analysis or venue-specific niches (Pacifica Print has three tools alone). The surface could be consolidated without losing capability.
Core workflows are covered — market data, account/position reads, trade preview/execute/close, funding and PnL analysis, options and outcomes. However, there is no cancel_order tool despite get_open_orders, and no order-status/history or leverage/margin modification, which are notable gaps for a trading server.
Maintenance
Related MCP Connectors
23-in-1 MCP server: EVM tx simulator, funding rate arb, macro radar, swap calldata & security.
Hyperliquid, Binance & Bybit perpetual funding rate arbitrage & DeFi APY yield scanner MCP.
Live perp funding rates across 6 venues (Hyperliquid, Binance, Bybit, Lighter...) and arbitrage.
Research-only MCP server: your AI as a quant research desk. 90 tools, no trades, no brokers.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP server that provides real-time data and insights from the Hyperliquid perp DEX for use in bots, dashboards, and analytics.1730MIT
- AlicenseAqualityDmaintenanceAn MCP server that streams K-line (candlestick) data from decentralized exchanges (DEXs) to power your AI agents and workflows.14MIT
- AlicenseAqualityDmaintenanceEnables AI agents to trade leveraged perpetual futures on Solana's Jupiter Perpetuals while providing tools for market data and technical analysis. It supports portfolio management, fee estimation, and automated position execution for SOL, ETH, and BTC using USDC collateral.132MIT
- AlicenseNot gradedqualityNot gradedmaintenanceAI-to-AI marketplace MCP server with 46 tools — swap 65+ crypto tokens on 7 chains, rent GPUs, trade 25 tokenized stocks, on-chain escrow (Solana + Base), DeFi yields, sentiment analysis, wallet monitoring, and image generation. Supports USDC payments across 14 blockchains.MIT