# liquidtrading-mcp

MCP server for the Liquid trading API. Enables AI agents to trade, read market data, and manage positions through any MCP-compatible client.

## Installation

### Prerequisites

- Python 3.10+
- [uv](https://docs.astral.sh/uv/getting-started/installation/) (recommended) or pip
- A Liquid API key and secret

### Install from PyPI

```bash
pip install liquidtrading-mcp
```

Or with uv:

```bash
uv pip install liquidtrading-mcp
```

### Install from Source

```bash
git clone https://github.com/your-org/liquidtrading-mcp.git
cd liquidtrading-mcp
uv sync --no-sources
```

For local development with sibling checkouts, plain `uv sync` will use the sibling `../liquidtrading-python` checkout via `tool.uv.sources`. If you are developing `liquidtrading-mcp` by itself, use `uv sync --no-sources` so `uv` resolves `liquidtrading-python` from PyPI instead.

## Configuration

### Claude Code

Run this command to add the MCP server to Claude Code:

```bash
claude mcp add liquid -- liquidtrading-mcp
```

Or with environment variables:

```bash
claude mcp add liquid \
  -e LIQUID_API_KEY=lq_... \
  -e LIQUID_API_SECRET=sk_... \
  -e MAX_ORDER_USD=1000 \
  -e DAILY_LOSS_LIMIT=5000 \
  -- liquidtrading-mcp
```

If running from source:

```bash
claude mcp add liquid \
  -e LIQUID_API_KEY=lq_... \
  -e LIQUID_API_SECRET=sk_... \
  -- uv run --directory /path/to/liquidtrading-mcp liquidtrading-mcp
```

### Claude Desktop

Open **Settings > Developer > Edit Config** and add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "liquid": {
      "command": "liquidtrading-mcp",
      "env": {
        "LIQUID_API_KEY": "lq_...",
        "LIQUID_API_SECRET": "sk_...",
        "MAX_ORDER_USD": "1000",
        "DAILY_LOSS_LIMIT": "5000"
      }
    }
  }
}
```

If running from source:

```json
{
  "mcpServers": {
    "liquid": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/liquidtrading-mcp", "liquidtrading-mcp"],
      "env": {
        "LIQUID_API_KEY": "lq_...",
        "LIQUID_API_SECRET": "sk_..."
      }
    }
  }
}
```

### Cursor

Open **Settings > MCP Servers > Add Server** and use the same JSON format as Claude Desktop above.

### Windsurf

Add to `~/.codeium/windsurf/mcp_config.json`:

```json
{
  "mcpServers": {
    "liquid": {
      "command": "liquidtrading-mcp",
      "env": {
        "LIQUID_API_KEY": "lq_...",
        "LIQUID_API_SECRET": "sk_..."
      }
    }
  }
}
```

### Verify Installation

After configuring, verify the server is working:

1. **Claude Code**: Run `claude mcp list` to see the server, then ask Claude to call `get_markets`
2. **Claude Desktop**: The tools icon (hammer) should show 22 tools from "Liquid Trading"
3. **MCP Inspector** (standalone debugging):
   ```bash
   npx @modelcontextprotocol/inspector liquidtrading-mcp
   ```
   Or from source:
   ```bash
   npx @modelcontextprotocol/inspector uv run --directory /path/to/liquidtrading-mcp liquidtrading-mcp
   ```
   This opens a web UI where you can list tools, call them interactively, and inspect schemas.

## Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `LIQUID_API_KEY` | Yes | None | API key |
| `LIQUID_API_SECRET` | Yes | None | API secret (must pair with key) |
| `LIQUID_BASE_URL` | No | SDK default | API base URL (must be valid HTTP/S) |
| `MAX_ORDER_USD` | No | 1000 | Max single order size in USD |
| `DAILY_LOSS_LIMIT` | No | 5000 | Daily cumulative loss cap in USD |
| `LIQUID_MCP_AUDIT_PATH` | No | ~/.liquidtrading-mcp/trades.jsonl | Audit log path |

**Notes:**
- `LIQUID_API_KEY` and `LIQUID_API_SECRET` are both required
- If `MAX_ORDER_USD` exceeds `DAILY_LOSS_LIMIT`, a warning is logged at startup
- The audit log directory is created automatically if it doesn't exist

## Tools (22)

### Market Data (read scope)
- `get_markets` — List all tradeable markets
- `get_ticker` — 24h ticker (price, volume, funding)
- `get_orderbook` — L2 order book
- `get_candles` — OHLCV candle data

### Account (read scope)
- `get_account` — Equity, margin, balance overview
- `get_balances` — Detailed balance breakdown
- `get_positions` — Open positions with PnL

### Orders (trade scope)
- `place_order` — Place market/limit order (size in USD notional)
- `place_bracket_order` — Order with mandatory TP/SL (atomic)
- `get_open_orders` — List open orders
- `get_order` — Get order by ID
- `cancel_order` — Cancel an order
- `cancel_all_orders` — Cancel all orders

### Positions (trade scope)
- `close_position` — Close full/partial position
- `set_tp_sl` — Set take-profit / stop-loss
- `update_leverage` — Change leverage (warns on >20x)
- `update_margin` — Adjust isolated margin

### Helpers
- `calculate_token_amount` — USD to token conversion
- `calculate_position_size` — % of equity to USD size
- `validate_trade` — Pre-flight risk check

## Resources

- `liquid://portfolio` — Current positions, equity, margin
- `liquid://risk` — Daily loss state, limits, exposure

## Prompt Templates

- `scalp` — Scalp trading strategy
- `swing` — Swing trading strategy
- `dca` — Dollar-cost averaging

## Safety

- **Max order size**: Rejects orders exceeding `MAX_ORDER_USD`
- **Daily loss limit**: Tracks cumulative losses per UTC day, blocks when exceeded
- **Dry run**: All trade tools accept `dry_run=True` for preview without executing
- **Audit log**: All trades logged to JSONL file (including dry runs)
- **High leverage warnings**: Orders and leverage changes above 20x trigger warnings
- **Error recovery**: All tools return structured errors with `hint` and `next_steps` for the agent to recover gracefully

## Transport

- Default: stdio (for Claude Desktop / Claude Code / Cursor)
- `liquidtrading-mcp --http`: Streamable HTTP on port 4243

## Troubleshooting

### SSL errors (`TLSV1_UNRECOGNIZED_NAME`)

Set `LIQUID_BASE_URL` to the correct API endpoint. The default URL may not resolve in all environments.

### Tools not appearing

1. Restart the MCP client after config changes
2. Check that `liquidtrading-mcp` is on your PATH: `which liquidtrading-mcp`
3. If installed from source, ensure the `--directory` path is correct
4. Check logs: Claude Code shows MCP errors in the output, Claude Desktop logs to `~/Library/Logs/Claude/`

### Authentication errors

- Verify both `LIQUID_API_KEY` and `LIQUID_API_SECRET` are set
- All endpoints require a valid API token — there are no unauthenticated routes
- The error response will include a `hint` field with recovery guidance
