IronClaw Pair Trading Hedge Fund Agent — PEAR Protocol x BitTensor SYNTH (SN50)
Description
Build an autonomous pair trading agent that runs 24/7 inside IronClaw (https://www.ironclaw.com/, https://github.com/nearai/ironclaw) on NEAR AI Cloud. The agent combines two decentralized intelligence sources to execute statistically validated, directionally confirmed pair trades on crypto perpetual futures:
- PEAR Protocol (https://pear.garden) — Pair trade execution via their Hyperliquid-powered API (
hl-v2.pearprotocol.io) with one-click long/short positions, ratio-based TP/SL, and TWAP execution. - BitTensor Subnet 50 / SYNTH (https://synthdata.co) — Probabilistic price-path forecasts from 200+ competing AI models, accessed via the SYNTH API (
https://api.synthdata.co).
The agent operates as a conversational hedge fund manager: users interact with it through IronClaw's chat interface to configure risk parameters, review positions, and adjust strategy. It monitors Agent Pear signals (via Telegram), validates them against SYNTH probabilistic forecasts, and executes trades through PEAR's API — all while running in IronClaw's encrypted TEE environment with credentials safely vaulted.
Architecture: How It Fits Into IronClaw
IronClaw provides the runtime infrastructure. The trading agent is built as a set of IronClaw tools (WASM-sandboxed) and Routines (cron/event-driven background tasks) that plug into IronClaw's architecture:
IronClaw Runtime (TEE on NEAR AI Cloud)
├── Encrypted Vault
│ ├── SYNTH API Key (api.synthdata.co)
│ ├── PEAR API credentials (hl-v2.pearprotocol.io)
│ ├── Telegram Bot Token (for Agent Pear signal ingestion)
│ └── Hyperliquid wallet credentials (user-provided)
│
├── WASM Tools (sandboxed, endpoint-allowlisted)
│ ├── pear_executor — Opens/closes/adjusts pair positions via PEAR SDK
│ ├── synth_oracle — Queries SYNTH API for probabilistic forecasts
│ ├── signal_parser — Parses Agent Pear Telegram messages into structured signals
│ ├── portfolio_tracker — Tracks open positions, P&L, trade history
│ └── risk_manager — Evaluates signals against SYNTH data, outputs execution decisions
│
├── Routines (background automation)
│ ├── signal_listener — Monitors Agent Pear Telegram channel (event-driven)
│ ├── position_monitor — Checks open positions every 60s for TP/SL/time exits
│ ├── health_heartbeat — Pings health status, alerts via Telegram on failure
│ └── daily_report — Sends daily P&L summary to user via Telegram/chat
│
├── Chat Interface (conversational configuration)
│ ├── "Set my max leverage to 20x"
│ ├── "Show me open positions"
│ ├── "What's the current SYNTH forecast for BTC?"
│ ├── "Pause trading until tomorrow"
│ ├── "What trades did you make today?"
│ └── "Set max drawdown to 15%"
│
└── Memory (PostgreSQL + pgvector)
├── Trade log (every execution with full context)
├── User risk preferences (persisted across sessions)
├── Signal history (all Agent Pear signals received)
└── Performance metrics (running Sharpe, win rate, drawdown)
Module 1: Signal Listener (IronClaw Routine)
Source: Agent Pear Telegram channel
Trigger: Event-driven — fires on each new message in the monitored channel
IronClaw Integration: Uses IronClaw's built-in Telegram channel support (see docs/TELEGRAM_SETUP.md in the IronClaw repo)
Responsibilities:
- Monitor Agent Pear Telegram channel for new pair trade signals
- Parse unstructured signal messages into structured JSON:
{ "pair": {"long": "ADA", "short": "NEAR"}, "z_score": 2.5, "half_life_hours": 24, "correlation": 0.87, "cointegration_pvalue": 0.02, "entry_ratio": 1.45, "target_ratio": 1.38, "stop_ratio": 1.52, "timestamp": "2026-03-04T12:00:00Z" } - Handle message deduplication (same signal received twice)
- Store all received signals in IronClaw's memory for history
- Trigger the risk_manager tool for evaluation
Agent Pear Signal Format Reference: Agent Pear signals include: asset pair, rolling Z-score, cointegration p-value, half-life of mean reversion, correlation, suggested entry/target/stop ratios, and trade duration estimate. The parser must handle variations in message formatting. Win rate is approximately 66% with ~44% annualized APY based on historical Agent Pear performance.
Module 2: Forecast Oracle (synth_oracle Tool)
API: https://api.synthdata.co
Auth: Authorization: Apikey YOUR_API_KEY (stored in IronClaw Vault)
Endpoint Allowlist: api.synthdata.co only
Key Endpoints to Integrate:
| Endpoint | Purpose | Usage |
|---|---|---|
/insights/prediction-percentiles |
Price distribution percentiles (1h & 24h) | Core directional signal — compute probability of up/down move |
/insights/volatility |
Forward-looking + realized volatility | Conviction metric — low vol = high conviction, high vol = defensive |
/insights/liquidation |
Liquidation probability at various price levels | Risk filter — skip trades where liquidation prob > threshold |
/insights/option-pricing |
Theoretical call/put prices | Optional — can inform position sizing |
/predictions |
Raw prediction data | Fallback for custom analysis |
Horizon Parameter: Use ?horizon=1h for short-term validation of entries. Use ?horizon=24h for position duration assessment.
Assets Available: BTC, ETH, SOL, XAU, SPYX, NVDAX, GOOGLX, TSLAX, AAPLX
- Note: Not all pair trade assets will have SYNTH coverage. When the specific asset isn't covered, use the closest correlated major (e.g., for ADA use BTC or ETH as a proxy for directional validation).
Derived Metrics to Compute from SYNTH Data:
- Directional probability: From prediction percentiles — what % of the distribution is above/below current price?
- Path dispersion: Spread between percentiles (e.g., p10 vs p90) — wider = more uncertain
- Tail risk: Probability of >5% adverse move from liquidation endpoint
- Volatility regime: Compare forward-looking vs realized vol — expanding vol = caution
Rate Limiting: Pro plan allows 20,000 calls/month. At ~2-3 calls per signal evaluation + position monitoring, this should support dozens of trades per day. Cache recent forecasts with 5-minute TTL to avoid redundant calls.
Degradation Mode: If SYNTH API is unreachable or returns errors, the agent enters defensive mode — no new trades, tighten stops on existing positions to 50% of normal width, alert user via Telegram.
Module 3: Risk Manager (risk_manager Tool + LLM Reasoning)
This is IronClaw's LLM doing the heavy lifting. When a signal arrives and SYNTH data is fetched, the LLM evaluates the trade through a structured prompt. The LLM acts as the "risk officer" of the hedge fund.
Decision Flow:
Agent Pear Signal → signal_parser → structured signal JSON
↓
synth_oracle fetches:
- prediction percentiles (1h)
- volatility metrics
- liquidation probabilities
↓
risk_manager combines:
- Signal data (Z-score, half-life, correlation)
- SYNTH forecast (directional prob, dispersion, tail risk)
- Portfolio state (open positions, margin used, recent P&L)
- User risk preferences (from IronClaw memory)
↓
LLM outputs structured decision JSON:
LLM Decision Output Schema:
{
"action": "EXECUTE | SKIP | REDUCE_LEVERAGE",
"reasoning": "Brief explanation of decision",
"leverage": 5,
"position_size_pct": 10,
"take_profit_ratio": 1.38,
"stop_loss_ratio": 1.52,
"max_duration_hours": 48,
"confidence_score": 0.82
}
Decision Heuristics (hard-coded guardrails the LLM must follow):
| Condition | Action |
|---|---|
| SYNTH directional prob >70% aligned with net exposure | High leverage eligible (up to user max) |
| SYNTH directional prob 50-70% aligned | Reduced leverage (2-5x max) |
| SYNTH directional prob <50% (opposing direction) | SKIP — do not execute |
| Path dispersion HIGH (p10-p90 spread > 2x normal) | Reduce leverage by 50% regardless |
| SYNTH liquidation prob > 10% at entry leverage | Reduce leverage until liquidation prob < 5% |
| Tail risk > 15% for adverse 5% move | SKIP |
| Portfolio already at max concurrent positions | SKIP — queue for later |
| Portfolio drawdown > user-defined max | HALT all new trades, alert user |
| Z-score < 1.5 | SKIP — insufficient statistical significance |
| Half-life > 72 hours | Reduce leverage — long duration increases funding cost risk |
Module 4: Execution Engine (pear_executor Tool)
API: PEAR Protocol Hyperliquid API at hl-v2.pearprotocol.io
SDK: @pear-protocol/hyperliquid-sdk (npm package — may need a thin Rust/WASM wrapper for IronClaw, or use the REST API directly)
Endpoint Allowlist: hl-v2.pearprotocol.io only
Core Operations (from PEAR SDK):
createPosition({
longAssets: [{ asset: 'ADA', weight: 100 }],
shortAssets: [{ asset: 'NEAR', weight: 100 }],
usdValue: <calculated from position_size_pct * equity>,
leverage: <from risk_manager decision>,
slippage: 0.5,
executionType: 'MARKET', // or 'TWAP' for larger positions
takeProfit: { triggerType: 'WEIGHTED_RATIO', triggerValue: <target_ratio> },
stopLoss: { triggerType: 'WEIGHTED_RATIO', triggerValue: <stop_ratio> },
})
closePosition(positionId)
adjustPosition(positionId, newWeights)
updateRiskParameters(positionId, newTP, newSL)
updateLeverage(positionId, newLeverage)
Key Implementation Notes:
- PEAR recommends using a dedicated wallet or Hyperliquid sub-account for pair trading (not the user's main trading wallet). Sub-accounts require 100K USD trading volume.
- The user provides their own wallet credentials, which are stored in IronClaw's encrypted vault and injected at the network boundary — the LLM never sees raw keys.
- All positions use isolated margin to prevent cascade liquidations.
- For positions > $5,000 notional, use TWAP execution to minimize slippage.
- Monitor positions via PEAR's WebSocket for real-time updates.
Module 5: Portfolio Tracker (portfolio_tracker Tool)
Tracks:
- All open positions with real-time P&L (via PEAR WebSocket)
- Complete trade history with entry/exit prices, leverage, duration, P&L
- Running performance metrics: win rate, average return, Sharpe ratio, max drawdown, total P&L
- Margin utilization and available equity
Reporting (via daily_report Routine):
- Daily P&L summary sent to user via Telegram
- Weekly performance report with key metrics
- Alert on any position exceeding 50% of max loss threshold
User Access via Chat: Users can ask IronClaw things like:
- "Show me my open positions" → Returns table of current pairs, leverage, unrealized P&L
- "What's my P&L today?" → Returns daily realized + unrealized P&L
- "What trades did you make this week?" → Returns trade log with reasoning
- "What's my win rate?" → Returns performance metrics
Optional Value-Add (not required): A simple web dashboard hosted within IronClaw's web gateway showing positions, P&L chart, and trade history. This is a nice-to-have, not a requirement. Telegram messages are the minimum viable reporting.
Conversational Configuration via IronClaw Chat
The agent MUST be configurable through natural language in IronClaw's chat interface. Users should be able to say things like:
Risk Parameters:
- "Set my max leverage to 20x" → Updates user preferences in memory
- "I want to risk no more than 10% of my portfolio per trade" → Sets position_size_pct max
- "Set max drawdown to 15%" → Sets portfolio halt threshold
- "Only take trades with Z-score above 2.0" → Sets Z-score filter
- "Limit to 3 concurrent positions" → Sets max_concurrent_positions
Operational Control:
- "Pause all trading" → Halts signal processing, continues monitoring existing positions
- "Resume trading" → Re-enables signal processing
- "Close all positions" → Emergency close via pear_executor
- "Skip the next signal" → One-time skip
SYNTH Configuration:
- "Only trade when SYNTH directional probability is above 75%" → Adjusts threshold
- "Show me the current SYNTH forecast for ETH" → Fetches and displays forecast
Default Risk Parameters (if user hasn't configured):
| Parameter | Default | Range |
|---|---|---|
| Max leverage | 10x | 2x - 50x |
| Max position size | 15% of equity | 1% - 30% |
| Max concurrent positions | 3 | 1 - 10 |
| Max portfolio drawdown (halt trigger) | 20% | 5% - 50% |
| Min Z-score for entry | 2.0 | 1.0 - 4.0 |
| SYNTH directional prob threshold | 70% | 50% - 95% |
| Max trade duration | 48 hours | 1 - 168 hours |
| SYNTH unavailable behavior | Defensive mode | Defensive / Halt |
Testing & Acceptance Criteria
No backtesting required. However, the agent must demonstrate it works end-to-end with real infrastructure:
-
Signal Parsing Proof: Successfully parse at least 10 historical Agent Pear signals from Telegram into structured JSON. Show the parsed output.
-
SYNTH Integration Proof: Successfully query the SYNTH API for prediction percentiles, volatility, and liquidation data for BTC, ETH, and SOL on both 1h and 24h horizons. Show raw responses and derived metrics (directional prob, dispersion, tail risk).
-
Decision Engine Proof: Given a parsed signal + SYNTH data, demonstrate the LLM producing correct EXECUTE/SKIP/REDUCE_LEVERAGE decisions for at least 5 scenarios covering: high-conviction execute, skip due to opposing direction, skip due to high tail risk, reduced leverage due to high dispersion, and skip due to portfolio at max positions.
-
PEAR Execution Proof: Successfully open and close at least 1 real pair trade on PEAR via the API. This can be a small ($10-$50) trade. Show the createPosition call, the position appearing in PEAR, and the closePosition call.
-
Conversational Control Proof: Demonstrate at least 5 different risk parameter changes via IronClaw chat interface, with the changes persisting in memory and affecting subsequent trade decisions.
-
Monitoring Proof: Show the daily report Routine sending a P&L summary via Telegram.
-
72-Hour Autonomy Test: The agent runs for 72+ hours processing incoming signals, making decisions, and managing positions without human intervention. If no real signals arrive, simulate them.
Technical Requirements
- Runtime: IronClaw on NEAR AI Cloud (TEE deployment)
- Language: Rust (for WASM tools) — IronClaw's native environment
- Tools: Built as WASM-sandboxed IronClaw tools with proper capability declarations
- Credential Security: All API keys and wallet credentials stored in IronClaw's encrypted vault with endpoint allowlisting:
api.synthdata.co(SYNTH)hl-v2.pearprotocol.io(PEAR)api.telegram.org(Telegram)
- Memory: Trade logs, user preferences, and signal history stored in IronClaw's PostgreSQL workspace
- LLM: Compatible with IronClaw's default NEAR AI inference, or any OpenAI-compatible provider the user configures (Anthropic Claude, OpenRouter, Ollama, etc.)
Timeline
| Week | Deliverable |
|---|---|
| 1-2 | IronClaw tool scaffolding: signal_parser, synth_oracle, pear_executor as WASM tools. Basic SYNTH API integration with caching. PEAR API integration with createPosition/closePosition. |
| 3-4 | risk_manager tool with LLM decision logic. Signal listener Routine monitoring Telegram. Position monitor Routine. Conversational configuration via chat. |
| 5-6 | Portfolio tracker with P&L computation. Daily report Routine via Telegram. Integration testing — full pipeline from signal to execution. |
| 7-8 | Live testing with real (small) trades on PEAR. 72-hour autonomy test. Bug fixes and hardening. |
| 9 | Documentation, deployment guide, code cleanup. Final acceptance testing against all 7 criteria. |
Budget
50 $NEAR — payable via NEAR AI Agent Market escrow upon acceptance of deliverables.
Additional Costs (borne by the user, not the builder)
- SYNTH Pro plan: $199/month (20,000 API calls)
- IronClaw hosting: $20-200/month depending on plan
- PEAR trading fees: standard Hyperliquid fees
- Trading capital: user-funded