Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<img src="https://img.shields.io/badge/strategies-19-C9A84C" alt="Strategies" />
<img src="https://img.shields.io/badge/tests-1300%2B%20passing-brightgreen" alt="Tests" />
<img src="https://img.shields.io/badge/license-MIT-blue" alt="License" />
<img src="https://img.shields.io/badge/MCP-20%20tools-8A2BE2" alt="MCP" />
<img src="https://img.shields.io/badge/MCP-21%20tools-8A2BE2" alt="MCP" />
</p>

<p align="center">
Expand Down Expand Up @@ -550,7 +550,7 @@ hl mcp serve # stdio transport (default)
hl mcp serve --transport sse # SSE transport
```

**20 MCP tools** for account state, trading, APEX/Radar/REFLECT, wallet/setup, safety actions (`schedule_cancel`, `emergency_close_all`), and agent memory/journal helpers. Run `hl mcp serve` to expose them to any MCP host.
**24 MCP tools** for account state, trading, CFI funding hedges, APEX/Radar/REFLECT, wallet/setup, safety actions (`schedule_cancel`, `emergency_close_all`), and agent memory/journal helpers. Run `hl mcp serve` to expose them to any MCP host.

Fast tools (strategies, builder, wallet, setup, memory, journal, judge) call Python directly — zero subprocess overhead.

Expand Down Expand Up @@ -619,7 +619,7 @@ Railway build root at the repo root.
```
cli/ CLI commands and trading engine
commands/ Subcommand modules (run, apex, radar, pulse, guard, reflect, house, ...)
mcp_server.py MCP server (20 tools via FastMCP)
mcp_server.py MCP server (24 tools via FastMCP)
hl_adapter.py Direct HL API adapter (live + mock)
builder_fee.py Builder fee config (HL native BuilderInfo)
keystore.py Encrypted keystore (geth-compatible)
Expand Down
87 changes: 84 additions & 3 deletions cli/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@
_READ_ONLY_TOOLS = {
"strategies", "builder_status", "wallet_list", "setup_check",
"account", "status", "apex_status",
"funding_hedge_propose", "funding_hedge_backtest",
"agent_memory", "trade_journal", "judge_report", "obsidian_context",
"order_status", "funding_rates",
}
# Tools that move funds or cancel/close live orders/positions — handle with care.
_DESTRUCTIVE_TOOLS = {
"trade", "run_strategy", "apex_run", "schedule_cancel", "emergency_close_all",
"trade", "run_strategy", "apex_run", "funding_hedge_execute",
"schedule_cancel", "emergency_close_all",
}
# Everything else (wallet_auto, radar_run, reflect_run) is
# state-changing-but-safe: neither a pure read nor fund-destructive.
Expand Down Expand Up @@ -357,8 +359,9 @@ def _ann(name: str, title: str):
instructions=(
"Autonomous Hyperliquid trading CLI — 14 strategies, APEX orchestrator, "
"REFLECT reviews. Always confirm details with the user before calling "
"destructive tools (trade, run_strategy, apex_run, schedule_cancel, "
"emergency_close_all). "
"destructive tools (trade, run_strategy, apex_run, funding_hedge_execute, "
"schedule_cancel, emergency_close_all). "
"funding_hedge_execute requires confirmed=true. "
"emergency_close_all requires confirm=true."
),
)
Expand Down Expand Up @@ -796,6 +799,84 @@ def funding_rates(
args.append("--mainnet")
return _run_hl(*args, env_overrides=_request_env(ctx))

@mcp.tool(**_ann("funding_hedge_propose", "Funding hedge proposal"))
def funding_hedge_propose(
coin: str = "BTC",
mainnet: bool = False,
ctx: FastMCPContext = None,
) -> str:
"""Build a CFI v2 funding hedge proposal without placing an order.

Args:
coin: Perp coin to hedge (for example BTC).
mainnet: Use mainnet instead of testnet.
"""
args = ["hedge", "propose", coin]
if mainnet:
args.append("--mainnet")
return _run_hl(*args, timeout=60, env_overrides=_request_env(ctx))

@mcp.tool(**_ann("funding_hedge_backtest", "Funding hedge backtest"))
def funding_hedge_backtest(
coin: str = "BTC",
days: int = 365,
notional: float = 1_000_000,
ctx: FastMCPContext = None,
) -> str:
"""Run the reference CFI v2 funding hedge backtest.

Args:
coin: Perp coin to backtest (for example BTC).
days: Backtest window; passed through for CLI compatibility.
notional: Source perp notional in USD.
"""
return _run_hl(
"hedge", "backtest",
"--coin", coin,
"--days", str(days),
"--notional", str(notional),
timeout=120,
env_overrides=_request_env(ctx),
)

@mcp.tool(**_ann("funding_hedge_execute", "Execute funding hedge"))
def funding_hedge_execute(
coin: str = "BTC",
dry_run: bool = False,
mainnet: bool = False,
confirmed: bool = False,
ctx: FastMCPContext = None,
) -> str:
"""Build and execute a CFI v2 funding hedge through `hl hedge execute`.

WARNING: with dry_run=False this can place a real CFI v2 hedge order.

Args:
coin: Perp coin to hedge (for example BTC).
dry_run: Preview the order only; no submit and no hedge-state write.
mainnet: Use mainnet instead of testnet.
confirmed: Must be true after explicit user approval.
"""
if not confirmed:
return _json_error("funding_hedge_execute requires confirmed=true after explicit user approval.")
env_overrides = _request_env(ctx)
error = _context_limit_error(
"funding_hedge_execute",
env_overrides,
mainnet=mainnet,
confirmed=confirmed,
require_signing=not dry_run,
)
if error:
return _json_error(error)
args = ["hedge", "execute", coin]
if dry_run:
args.append("--dry-run")
if mainnet:
args.append("--mainnet")
args.append("--yes")
return _run_hl(*args, timeout=120, env_overrides=env_overrides)

# ------------------------------------------------------------------
# Self-improvement tools — memory, journal, judge, obsidian
# ------------------------------------------------------------------
Expand Down
34 changes: 23 additions & 11 deletions cli/skill.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: yex-trader
description: Autonomous Hyperliquid trading — 14 strategies (MM, momentum, arbitrage, LLM) with APEX multi-slot orchestrator, REFLECT performance review, DSL trailing stops, and builder fee revenue collection.
description: Autonomous Hyperliquid trading — 19 strategies (MM, momentum, arbitrage, LLM) with APEX multi-slot orchestrator, REFLECT performance review, Guard trailing stops, and builder fee revenue collection.
user-invocable: true
argument-hint: "<strategy> [options]"
allowed-tools:
Expand All @@ -17,7 +17,7 @@ metadata:

# YEX Trader

Autonomous Hyperliquid trading via agent-cli. 14 strategies across market making, momentum, arbitrage, and LLM-powered trading. APEX multi-slot orchestrator. REFLECT nightly performance review. Builder fee revenue collection.
Autonomous Hyperliquid trading via agent-cli. 19 strategies across market making, momentum, arbitrage, and LLM-powered trading. APEX multi-slot orchestrator. REFLECT nightly performance review. Builder fee revenue collection.

## Quick Start (Agent-Friendly)

Expand Down Expand Up @@ -137,13 +137,12 @@ hl reflect report [--date 2026-03-03]
hl reflect history [-n 10]
```

### Dynamic Stop Loss (DSL)
### Guard Trailing Stop

```bash
hl dsl start <instrument> [--entry-price 2500] [--direction long] [--preset tight|standard|wide]
hl dsl check <instrument>
hl dsl status
hl dsl presets
hl guard start ETH-PERP --entry 2500 --size 1 --direction long [--preset tight|moderate]
hl guard status
hl guard presets
```

### Radar & Movers
Expand Down Expand Up @@ -179,16 +178,16 @@ hl setup bootstrap # Auto-create venv and install
hl setup claim-usdyp # Claim testnet USDyP tokens
```

### MCP Server (16 Tools)
### MCP Server (~24 Tools)

```bash
hl mcp serve # Start MCP server (stdio transport)
hl mcp serve --transport sse # Start MCP server (SSE transport)
```

Tools: `strategies`, `builder_status`, `wallet_list`, `wallet_auto`, `setup_check`, `account`, `status`, `trade`, `run_strategy`, `radar_run`, `apex_status`, `apex_run`, `reflect_run`, `agent_memory`, `trade_journal`, `judge_report`
Tools: `strategies`, `builder_status`, `wallet_list`, `wallet_auto`, `setup_check`, `account`, `status`, `trade`, `run_strategy`, `radar_run`, `apex_status`, `apex_run`, `reflect_run`, `schedule_cancel`, `emergency_close_all`, `order_status`, `funding_rates`, `funding_hedge_propose`, `funding_hedge_backtest`, `funding_hedge_execute`, `agent_memory`, `trade_journal`, `judge_report`, `obsidian_context`

## Strategies (14)
## Strategies (19)

| Name | Type | Description |
|------|------|-------------|
Expand All @@ -204,13 +203,26 @@ Tools: `strategies`, `builder_status`, `wallet_list`, `wallet_auto`, `setup_chec
| momentum_breakout | Signal | Enters on volume + price breakout above/below N-period range |
| aggressive_taker | Taker | Directional spread crossing with bias |
| hedge_agent | Risk | Reduces excess exposure per deterministic mandate |
| cfi_hedge | Risk | CFI-v2 funding-cost hedge (YEX testnet / Paragon mainnet BTCSWP) |
| rfq_agent | RFQ | Block-size dark RFQ liquidity |
| claude_agent | LLM | Claude/Gemini-powered autonomous trading agent |
| simplified_ensemble | Signal | 6-signal ensemble vote |
| funding_momentum | Signal | Funding rate mean-reversion with EMA confirmation |
| oi_divergence | Signal | Price/OI divergence filter |
| trend_follower | Signal | EMA crossover + ADX trend strength filter |

## Instruments

- **Standard perps**: ETH-PERP, BTC-PERP, SOL-PERP, etc.
- **YEX yield markets**: VXX-USDYP (yex:VXX), US3M-USDYP (yex:US3M)
- **YEX yield markets (testnet)**: VXX-USDYP (`yex:VXX`), US3M-USDYP (`yex:US3M`), BTCSWP-USDYP (`yex:BTCSWP`)
- **Paragon BTCSWP swap perps (HIP-3)**:

| Network | Instrument | HL coin | Notes |
|---------|------------|---------|-------|
| Testnet | `BTCSWP-OSRS` | `osrs:BTCSWP` | Paragon swap perp on the `osrs` dex |
| Mainnet | `BTCSWP-PARA` | `para:BTCSWP` | Paragon swap perp on the `para` dex |

Shorthand `BTCSWP` resolves by network: testnet → `BTCSWP-USDYP` (YEX yield), mainnet → `BTCSWP-PARA`. Use `BTCSWP-OSRS` or `osrs:BTCSWP` for the explicit Paragon swap perp on testnet.

## Workflow

Expand Down
6 changes: 5 additions & 1 deletion deploy/hermes-railway/workspace/TOOLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## MCP Server: nunchi_trading

The primary tool provider, registered in `config.yaml` under `mcp_servers.nunchi_trading`. Exposes 13 trading tools via Model Context Protocol:
The primary tool provider, registered in `config.yaml` under `mcp_servers.nunchi_trading`. Exposes 24 trading tools via Model Context Protocol, including:

- `account` — Show HL account state (balance, margin, positions)
- `status` — Current positions, PnL, and risk state
Expand All @@ -17,6 +17,10 @@ The primary tool provider, registered in `config.yaml` under `mcp_servers.nunchi
- `builder_status` — Check builder fee approval status
- `wallet_list` — List available wallets
- `wallet_auto` — Create wallet automatically
- `funding_rates` — Read current funding rates
- `funding_hedge_propose` — Build a CFI v2 funding hedge proposal
- `funding_hedge_backtest` — Run the reference funding hedge backtest
- `funding_hedge_execute` — Execute or dry-run a CFI v2 hedge; requires `confirmed=true`

## CLI: hl

Expand Down
6 changes: 5 additions & 1 deletion deploy/openclaw-railway/workspace/TOOLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ mcporter call nunchi_trading.account # call a tool (no args)
mcporter call nunchi_trading.trade instrument=ETH-PERP side=buy size=0.1
```

Exposes 13 trading tools via Model Context Protocol:
Exposes 24 trading tools via Model Context Protocol, including:

- `account` — Show HL account state (balance, margin, positions)
- `status` — Current positions, PnL, and risk state
Expand All @@ -26,6 +26,10 @@ Exposes 13 trading tools via Model Context Protocol:
- `builder_status` — Check builder fee approval status
- `wallet_list` — List available wallets
- `wallet_auto` — Create wallet automatically
- `funding_rates` — Read current funding rates
- `funding_hedge_propose` — Build a CFI v2 funding hedge proposal
- `funding_hedge_backtest` — Run the reference funding hedge backtest
- `funding_hedge_execute` — Execute or dry-run a CFI v2 hedge; requires `confirmed=true`

## CLI: hl

Expand Down
77 changes: 77 additions & 0 deletions docs/MCP_PRICING_MEASUREMENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# MCP Pricing Measurements

Measured on 2026-07-01 for the hosted MCP tools runner path.

## Harness

Run:

```bash
python3 scripts/pricing_measure.py --output tmp/pricing-measurement-local.json
railway run --service hosted-trading-mcp --environment production -- python3 scripts/pricing_measure.py --output tmp/pricing-measurement-runner-env.json
```

Use `--openrouter-live` only when spending OpenRouter credits is intended.

## Results

Production runner env dry-run:

- `RUN_MODE=mcp`, `HL_TESTNET=true`.
- `python.import_cli`: 58.6 ms.
- MCP `strategies`: 118.7 ms, 3,068 response bytes.
- MCP `funding_hedge_execute` without `confirmed=true`: 0.09 ms refusal, no order path.
- Railway resource metrics, last 1h: `<0.01 vCPU`, 15 MB memory, 0 MB network, 0 MB disk.

Local Task 7 dry-run (`tmp/pricing-measurement-task7-local.json`):

- `python.import_cli`: 69.7 ms.
- MCP `tools/list`: 0.01 ms, 24 hosted runner tools surfaced by the JSON-RPC wrapper.
- MCP `setup_check`: 7.9 ms.
- MCP `strategies`: 166.8 ms, 3,068 response bytes.
- MCP `trade` without signing context: 0.09 ms refusal. This is the safe
noninteractive confirmation/hang check; no subprocess order path was entered.
- MCP `funding_hedge_execute` without `confirmed=true`: 0.03 ms refusal.

The pricing harness now emits the full Task 7 classification:

- Free/read: 15 tools.
- Paid compute/inference cost centers: 5 tools.
- Safety-gated/fund-moving/wallet-write: 7 tools, or 6 if `wallet_auto` is
excluded from the costable 26-tool surface because it is disabled on the
hosted keyless runner.
- Recommended beta free cap: about 20 hosted MCP discovery/read calls before
subscription or upgrade nudges.

## Economics

Mode 1, hosted MCP tools:

- `C_seat` is not computed yet. Railway metrics expose CPU/memory/network, but not monthly billing cost. Set `RAILWAY_SHARED_RUNTIME_MONTHLY_USD` or pass `--runtime-monthly-usd` once billing data is available.

Mode 2, hosted MCP tools plus Nunchi/OpenRouter inference:

- No live OpenRouter spend was measured because `OPENROUTER_API_KEY` is not present in the runner env and `--openrouter-live` was not run.
- Current inference budgets remain inputs only: Starter `$10`, Growth `$50`, Team `$250`.
- Anchor estimates from the Task 7 prompt:
- `openai/gpt-4.1-mini` at about `$0.0002` per heartbeat gives about
50,000 / 250,000 / 1,250,000 heartbeats for Starter / Growth / Team.
- `openrouter/auto` at about `$0.0037` per heartbeat gives about
2,703 / 13,514 / 67,568 heartbeats.
- Fusion at about `$0.033` per capped run, provided as about 146x mini, gives
about 303 / 1,515 / 7,576 runs.

Mode 3, clone/local plus builder economics:

- No funded-wallet fill measurement was run because the production runner has no `HL_PRIVATE_KEY`, `HL_KEYSTORE_PASSWORD`, or `~/.hl-agent/env`.
- Formulaic builder-fee economics at the default `BUILDER_FEE_TENTHS_BPS=100` are `$100` per `$100,000` notional and `$1,000` per `$1,000,000` notional.
- `trade` itself should remain free or low-friction from a pricing standpoint:
it is safety-sensitive, not inference-heavy, and it is the path that can
produce builder-code/builder-fee economics. Gate it with confirmation,
builder-code validation, network consent, size limits, and signing context.

## Blockers

- Missing Railway monthly billing cost input for Mode 1 `C_seat`.
- Missing `OPENROUTER_API_KEY` for Mode 2 inference spend.
- Missing funded-wallet/HL signing credentials for live fills and builder-fee realization.
Loading