pear-protocol

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

🍐 Pear Protocol — Headless (agent wallet)

🍐 Pear Protocol — 无头(Agent钱包)

Pair/basket trading on top of Hyperliquid: open a long and a short leg as one synthetic position. This skill uses HEADLESS auth only — the agent's own Privy wallet signs a SIWE login against the V3 gateway; no browser, no OAuth, no user interaction. Works out of the box for any Starchild agent.
在Hyperliquid之上进行配对/篮子交易:将做多和做空两个仓位作为一个合成仓位开立。本技能仅使用无头认证——Agent自有Privy钱包针对V3网关签署SIWE登录信息;无需浏览器、无需OAuth、无需用户交互。适用于任何Starchild Agent,开箱即用。

Endpoints

端点

  • V3 gateway (REST):
    https://pro-gateway.pearprotocol.io
  • Orchard MCP:
    https://mcp.pearprotocol.io/mcp
    (streamable HTTP, stateless — accepts
    x-api-key
    directly; docs: https://docs.pear.garden)
  • V3网关(REST):
    https://pro-gateway.pearprotocol.io
  • Orchard MCP:
    https://mcp.pearprotocol.io/mcp
    (可流式传输的HTTP,无状态——直接接受
    x-api-key
    ;文档:https://docs.pear.garden)

Auth —
scripts/gateway.py
(use this, don't hand-roll curl)

认证 —
scripts/gateway.py
(请使用此脚本,不要手动编写curl命令)

bash
python3 skills/pear-protocol/scripts/gateway.py login        # SIWE login w/ agent wallet, caches tokens
python3 skills/pear-protocol/scripts/gateway.py status       # identity + token validity
python3 skills/pear-protocol/scripts/gateway.py ensure-key   # mint PEAR_API_KEY into .env (once)
python3 skills/pear-protocol/scripts/gateway.py markets --limit 15
python3 skills/pear-protocol/scripts/gateway.py get /trade-accounts
python3 skills/pear-protocol/scripts/gateway.py post <path> '<json>'   # writes; auto Bearer
Flow:
POST /auth/nonce {address}
wallet.wallet_sign(message)
(EIP-191; gateway accepts the smart-wallet address even though personal_sign recovers to the underlying EOA — no EIP-1271 issue) →
POST /auth/login {method:"wallet",address,signature}
accessToken
(JWT ~15 min, auto-refresh/re-login). Tokens cached in
workspace/.pear/gateway_tokens.json
(0600). Single-flight nonce→login: concurrent nonce requests rotate the nonce and 401 the earlier signature.
bash
python3 skills/pear-protocol/scripts/gateway.py login        # 使用Agent钱包进行SIWE登录,缓存令牌
python3 skills/pear-protocol/scripts/gateway.py status       # 身份信息 + 令牌有效性
python3 skills/pear-protocol/scripts/gateway.py ensure-key   # 将PEAR_API_KEY写入.env文件(仅需执行一次)
python3 skills/pear-protocol/scripts/gateway.py markets --limit 15
python3 skills/pear-protocol/scripts/gateway.py get /trade-accounts
python3 skills/pear-protocol/scripts/gateway.py post <path> '<json>'   # 写入操作;自动添加Bearer令牌
流程:
POST /auth/nonce {address}
wallet.wallet_sign(message)
(EIP-191;网关接受智能钱包地址,即使personal_sign恢复到底层EOA——无EIP-1271问题)→
POST /auth/login {method:"wallet",address,signature}
accessToken
(JWT,有效期约15分钟,自动刷新/重新登录)。令牌缓存于
workspace/.pear/gateway_tokens.json
(权限0600)。单次流程:nonce请求→登录:并发nonce请求会轮换nonce并使较早的签名返回401。

Which credential for which call

不同调用对应的凭证

Call typeAuthNotes
Gateway reads (markets, funding)
x-api-key: $PEAR_API_KEY
persistent, read scope
Gateway writes (orders, trade-accounts)
Authorization: Bearer …
api_key → 403; gateway.py auto-refreshes
Account-scoped calls+
x-trade-account-id: <id>
mandatory once >1 account
MCP server
x-api-key
directly
gateway wallet Bearer is REJECTED on MCP (different token type)
  • GET /markets
    REQUIRES
    ?connector=hyperliquid
    (291 markets: price, funding, OI, 24h vol/change).
调用类型认证方式说明
网关读取操作(市场、资金费率)
x-api-key: $PEAR_API_KEY
持久有效,仅读取权限
网关写入操作(订单、交易账户)
Authorization: Bearer …
使用api_key会返回403;gateway.py会自动刷新令牌
账户范围调用+
x-trade-account-id: <id>
当存在多个账户时为必填项
MCP服务器直接使用
x-api-key
网关钱包的Bearer令牌在MCP上会被拒绝(令牌类型不同)
  • GET /markets
    必须携带
    ?connector=hyperliquid
    参数(共291个市场:价格、资金费率、持仓量、24小时成交量/涨跌幅)。

API-key scopes gate the MCP tool surface

API密钥权限管控MCP工具范围

POST /api-keys
(Bearer) body
{"label": "...", "scope": "read"|"read_write"}
(field is
label
NOT
name
; raw key returned ONCE). Read key → 16 analytics/account tools.
read_write
→ 32 tools, adding trading: plan/execute pairs for open_basket, close_basket, set_position_tpsl, rebalance_position, adjust_position, enable_auto_rebalance, plus sync_account, cancel_pending_order, manage_saved_basket.
Convention: store the read key as
PEAR_API_KEY
and (if trading) a read_write key as
PEAR_API_KEY_RW
in workspace/.env. For MCP trading, export
PEAR_API_KEY=$PEAR_API_KEY_RW
before calling
pear_mcp.py
.
POST /api-keys
(Bearer令牌)请求体
{"label": "...", "scope": "read"|"read_write"}
(字段为
label
而非
name
;原始密钥仅返回一次)。只读密钥可访问16个分析/账户工具。
read_write
密钥可访问32个工具,新增交易功能:plan/execute pairs用于open_basket、close_basket、set_position_tpsl、rebalance_position、adjust_position、enable_auto_rebalance,以及sync_account、cancel_pending_order、manage_saved_basket。
约定:将只读密钥存储为
.env
中的
PEAR_API_KEY
,若需交易则将读写密钥存储为
PEAR_API_KEY_RW
。对于MCP交易,在调用
pear_mcp.py
前导出
PEAR_API_KEY=$PEAR_API_KEY_RW

MCP client —
scripts/pear_mcp.py

MCP客户端 —
scripts/pear_mcp.py

bash
python3 skills/pear-protocol/scripts/pear_mcp.py status
python3 skills/pear-protocol/scripts/pear_mcp.py list
python3 skills/pear-protocol/scripts/pear_mcp.py call <tool> '<json-args>'
Auto-uses
PEAR_API_KEY
from env/.env (x-api-key header). Read tools: get_position(+history), discover_assets, list_baskets, search_prediction_markets, get_leaderboard, list_trade_accounts, get_account_summary, get_fee_quote, get_tca, list_pending_orders, etc.
bash
python3 skills/pear-protocol/scripts/pear_mcp.py status
python3 skills/pear-protocol/scripts/pear_mcp.py list
python3 skills/pear-protocol/scripts/pear_mcp.py call <tool> '<json-args>'
自动使用环境变量/.env中的
PEAR_API_KEY
(x-api-key请求头)。只读工具包括:get_position(+历史记录)、discover_assets、list_baskets、search_prediction_markets、get_leaderboard、list_trade_accounts、get_account_summary、get_fee_quote、get_tca、list_pending_orders等。

Trade account (Hyperliquid) — REQUIRED before any execute_*

交易账户(Hyperliquid)—— 执行任何execute_*操作前必须设置

One-time setup per agent (the connected account id is returned at step 3; keep it in
.pear/trade_account.json
):
  1. Generate keypair (
    eth_account.Account.create()
    ) → save to
    .pear/hl_signer.json
    (0600).
  2. Approve as HL agent wallet — user-signed
    approveAgent
    action, EIP-712 domain
    HyperliquidSignTransaction
    (chainId 421614), types
    HyperliquidTransaction:ApproveAgent
    [hyperliquidChain, agentAddress, agentName, nonce] — signed by the Privy master via wallet service
    /agent/sign-typed-data
    (same pattern as hyperliquid skill's
    sign_user_action
    ). Submit to
    POST api.hyperliquid.xyz/exchange
    with
    signatureChainId: "0x66eee"
    (used even on Mainnet — the
    hyperliquidChain
    field selects the network; use that). 42161 /
    0xa4b1
    is also accepted and was verified working — the real requirement is that
    signatureChainId
    exactly matches the domain chainId used when signing. Verify with info
    {"type":"extraAgents","user":<master>}
    .
  3. POST /trade-accounts
    (Bearer) — EXACT payload (validation errors only show details when
    connector
    is present):
    {"alias": "...", "connector": "hyperliquid", "exchangeIdentifier": <master addr>, "credentials": {"signer_key": <signer priv, snake_case!>}, "metadata": {"agentWalletAddress": <signer addr>, "isSubaccount": false, "mainAccountAddress": <master addr>}}
    → 201 with
    account.id
    .
Funds stay under the master HL account; signer trades, can't withdraw.
  1. Approve Pear's builder fee (REQUIRED — executions fail without it). Pear does NOT do this for you. Get the builder address via MCP
    get_fee_recipient {"connector":"hyperliquid"}
    (currently
    0xa47d4d99191db54a4829cdf3de2417e527c3b042
    , fee 6 bps). Sign a user-signed
    approveBuilderFee
    action with the MASTER wallet (not the signer): EIP-712 type
    HyperliquidTransaction:ApproveBuilderFee
    [hyperliquidChain, maxFeeRate, builder, nonce], same domain/chain-id rules as approveAgent. Use
    maxFeeRate: "0.1%"
    (HL perps cap). Submit to
    POST api.hyperliquid.xyz/exchange
    with matching
    signatureChainId
    . Verify: info
    {"type":"maxBuilderFee","user":<master>,"builder":<builder>}
    must return > 0 (100 = 0.1%).
每个Agent只需执行一次设置(连接的账户ID会在步骤3返回;请保存到
.pear/trade_account.json
):
  1. 生成密钥对(
    eth_account.Account.create()
    )→ 保存到
    .pear/hl_signer.json
    (权限0600)。
  2. 批准为HL Agent钱包——由用户签署
    approveAgent
    操作,EIP-712域为
    HyperliquidSignTransaction
    (链ID 421614),类型为
    HyperliquidTransaction:ApproveAgent
    [hyperliquidChain, agentAddress, agentName, nonce] —— 通过钱包服务
    /agent/sign-typed-data
    由Privy主钱包签署(与hyperliquid技能的
    sign_user_action
    模式相同)。提交至
    POST api.hyperliquid.xyz/exchange
    ,并携带
    signatureChainId: "0x66eee"
    (即使在主网也使用该值——
    hyperliquidChain
    字段选择网络;请使用该值)。42161 /
    0xa4b1
    也可接受并已验证可用——实际要求是
    signatureChainId
    必须与签名时使用的域链ID完全匹配。通过信息
    {"type":"extraAgents","user":<master>}
    验证。
  3. POST /trade-accounts
    (Bearer令牌)—— 精确请求体(仅当存在
    connector
    时才会显示验证错误详情):
    {"alias": "...", "connector": "hyperliquid", "exchangeIdentifier": <master addr>, "credentials": {"signer_key": <signer priv, snake_case!>}, "metadata": {"agentWalletAddress": <signer addr>, "isSubaccount": false, "mainAccountAddress": <master addr>}}
    → 返回201状态码及
    account.id
资金仍存于主HL账户;签名者可进行交易,但无法提取资金。
  1. 批准Pear的构建者费用(必须设置——未批准则执行操作会失败)。 Pear不会自动完成此操作。通过MCP
    get_fee_recipient {"connector":"hyperliquid"}
    获取构建者地址(当前为
    0xa47d4d99191db54a4829cdf3de2417e527c3b042
    ,费率为6个基点)。使用主钱包(而非签名者)签署用户操作
    approveBuilderFee
    :EIP-712类型为
    HyperliquidTransaction:ApproveBuilderFee
    [hyperliquidChain, maxFeeRate, builder, nonce],域/链ID规则与approveAgent相同。使用
    maxFeeRate: "0.1%"
    (HL永续合约上限)。提交至
    POST api.hyperliquid.xyz/exchange
    并携带匹配的
    signatureChainId
    。验证:信息
    {"type":"maxBuilderFee","user":<master>,"builder":<builder>}
    必须返回大于0的值(100 = 0.1%)。

Trading via MCP — plan → execute pattern

通过MCP交易——规划→执行模式

Arg shape:
{"tradeAccountId": <id>, "params": {...}}
params
is a discriminated union on
executionStyle
(market|twap|trigger|ladder). Legs:
{"source":"symbol","symbol":"BTC","side":"BUY"|"SELL"}
+ top-level
totalUsd
,
leverage
,
marginMode
.
plan_*
= dry-run with priced legs/margin (ALWAYS show the user before executing);
execute_*
= live. HL $10 min notional per leg (auto-bumped with warning).
Preflight (run before every execute_*):
python3 scripts/preflight.py check --notional <usd> [--leverage N]
Verifies: API key, trade account, on-chain builder-fee approval, balance breakdown (perp equity vs spot — catches funds stuck in spot / account-mode issues that zero out margin on xyz:* builder-DEX markets), and available margin vs the planned notional. Exit 0 = safe to execute; nonzero = blocked with the specific reason. Do NOT execute on a failing preflight.
Post-trade receipt (run after every execute_*):
python3 scripts/preflight.py verify <execution_id> --trade-account <id>
Checks execution status + venue errors + filledQuantity + that the position actually exists. Only "FILLED ✅" means a trade happened.
⚠️
status: executed
≠ filled.
The execute_* response only means Pear submitted the order. ALWAYS verify the outcome: check the execution record for venue errors and
filledQuantity > 0
, then confirm the position exists (get_position / HL clearinghouseState). A common definitive rejection is
"Builder fee has not been approved"
→ run step 4 of the trade-account recipe, then retry.
get_account_summary
args:
{"tradeAccountId": <id>, "params": {"scope": "balance"}}
.
参数格式:
{"tradeAccountId": <id>, "params": {...}}
——
params
是基于
executionStyle
(market|twap|trigger|ladder)的区分联合类型。仓位腿:
{"source":"symbol","symbol":"BTC","side":"BUY"|"SELL"}
+ 顶层字段
totalUsd
leverage
marginMode
plan_*
= 带定价仓位腿/保证金的试运行(执行前必须展示给用户);
execute_*
= 实盘交易。HL每条仓位腿最低名义价值为10美元(若不足会自动调整并给出警告)。
预检查(每次执行execute_*前运行):
python3 scripts/preflight.py check --notional <usd> [--leverage N]
验证:API密钥、交易账户、链上构建者费用批准、余额明细(永续合约权益 vs 现货——捕获资金被困在现货/账户模式问题,这些问题会导致xyz:*构建者DEX市场的保证金归零),以及可用保证金与计划名义价值的对比。退出码0 = 可安全执行;非零 = 因特定原因被阻止。预检查失败时不要执行交易。
交易后确认(每次执行execute_*后运行):
python3 scripts/preflight.py verify <execution_id> --trade-account <id>
检查执行状态 + 场所错误 + 成交数量 + 仓位是否实际存在。只有“FILLED ✅”表示交易已完成。
⚠️
status: executed
≠ 成交。
execute_*的响应仅表示Pear已提交订单。必须始终验证结果:检查执行记录中的场所错误和
filledQuantity > 0
,然后确认仓位存在(get_position / HL clearinghouseState)。常见的明确拒绝是
"Builder fee has not been approved"
→ 完成交易账户设置的步骤4,然后重试。
get_account_summary
参数:
{"tradeAccountId": <id>, "params": {"scope": "balance"}}

Notes

注意事项

Troubleshooting

故障排除

  • Builder-fee approval has cache propagation delay. After on-chain
    maxBuilderFee
    verifies > 0, Pear's venue check may still reject briefly ("Builder fee has not been approved") — wait ~1–2 min and retry before debugging further.
  • xyz: (HIP-3 builder-DEX) markets show $0 margin until unified account abstraction is enabled* on the Hyperliquid account. If a plan prices fine but available margin reads zero on an xyz pair, enable unified/abstracted account mode first, then re-plan.
  • Account-scoped gateway/MCP calls (positions, account summary, execute_*) fail until a trade account is connected — expected; follow the trade-account recipe first. Market data and analytics tools work without one.
  • Importing the wallet module may print harmless warnings about unavailable optional analytics integrations (e.g. CoinGecko/Coinglass) — ignore them; they don't affect Pear.
  • Scripts auto-route HTTP through Starchild's authenticated proxy when available and fall back to direct connections otherwise; no configuration needed.
  • 构建者费用批准存在缓存传播延迟。 当链上
    maxBuilderFee
    验证大于0后,Pear的场所检查可能仍会短暂拒绝(“Builder fee has not been approved”)——等待约1-2分钟后重试,再进行进一步调试。
  • xyz:*(HIP-3构建者DEX)市场在Hyperliquid账户启用统一账户抽象前显示0美元保证金。若某个计划定价正常但xyz配对的可用保证金显示为0,请先启用统一/抽象账户模式,然后重新规划。
  • 账户范围的网关/MCP调用(仓位、账户摘要、execute_*)在连接交易账户前会失败——此为预期行为;请先完成交易账户设置流程。市场数据和分析工具无需交易账户即可使用。
  • 导入钱包模块可能会打印关于可选分析集成(如CoinGecko/Coinglass)不可用的无害警告——忽略即可;这些不影响Pear的使用。
  • 脚本会自动通过Starchild的认证代理路由HTTP请求(若可用),否则回退到直接连接;无需额外配置。