# Purrio CLI

Terminal interface for Hyperliquid. Built for traders and automation.

## What it does

Purrio is a command-line wrapper around Hyperliquid's Python SDK. It lets you trade, check positions, and query market data from your terminal. The output formats (table/json/csv) make it easy to use in scripts, trading bots, or AI agents.

## Features

- **Terminal Trading**: Execute trades and monitor positions from the command line
- **Multiple Output Formats**: Table (human), JSON (scripts), CSV (spreadsheets)
- **Scriptable**: No interactive prompts - everything via flags for automation
- **Simple Wrapper**: Thin layer over Hyperliquid's Python SDK
- **Modular Design**: Commands organized into logical groups (info, trade, config)

## Commands Overview

```bash
# Information Commands
purrio coins               # List all available trading pairs
purrio price [COINS...]   # Get current prices
purrio positions ADDRESS    # View positions for any wallet
purrio orders ADDRESS       # View open orders
purrio fills ADDRESS        # View recent trades
purrio account ADDRESS      # View account summary
purrio funding COIN         # Get funding rate history
purrio orderbook COIN       # Get order book depth
purrio meta COIN            # Get asset info (leverage, decimals)
purrio asset-ctx [COIN]     # Get asset context with market data

# Trading Commands (requires credentials)
purrio long COIN LEVERAGE MARGIN          # Open long position
purrio short COIN LEVERAGE MARGIN         # Open short position
purrio close COIN PERCENTAGE              # Close position
purrio close all PERCENTAGE               # Close all positions

# Limit Order Commands
purrio limit long COIN LEVERAGE PRICE MARGIN    # Place long limit order
purrio limit short COIN LEVERAGE PRICE MARGIN   # Place short limit order
purrio limit cancel COIN ORDER_ID               # Cancel specific order
purrio limit cancel COIN --all                  # Cancel all orders for coin

# Configuration
purrio config show              # Display current configuration
purrio version                  # Show version
```

## Installation

```bash
# Using pip
pip install purrio

# Using poetry
poetry add purrio

# From source
git clone https://github.com/purrio/purrio-cli.git
cd purrio-cli
poetry install
```

## Quick Start

### Get Prices

```bash
# All prices
purrio price

# Specific coins
purrio price BTC ETH

# JSON output for scripts
purrio --output json price BTC
```

### View Positions

```bash
# Any wallet address
purrio positions 0x1234...

# JSON format
purrio --output json positions 0x1234...
```

### Open Positions

```bash
# Set up credentials
export PURRIO_ACCOUNT_ADDRESS=0x...
export PURRIO_SECRET_KEY=0x...

# Open long position
purrio long BTC 5x 1000     # 5x leverage, $1000 margin

# Open short position
purrio short ETH 3x 2000    # 3x leverage, $2000 margin

# Close positions
purrio close BTC 100%       # Close BTC position completely
purrio close all 50%        # Close 50% of all positions
```

### Limit Orders

```bash
# Place limit orders with leverage and margin
purrio limit long BTC 5x 50000 1000     # Long BTC at $50k, 5x leverage, $1000 margin
purrio limit short ETH 3x 3000 2000     # Short ETH at $3k, 3x leverage, $2000 margin

# With options
purrio limit long SOL 10x 100 500 --tif Ioc --reduce-only
```

## Configuration

### Environment Variables

Create a `.env` file or set environment variables:

```bash
# Required for trading
PURRIO_ACCOUNT_ADDRESS=0x...  # Your wallet address
PURRIO_SECRET_KEY=0x...        # Your private key

# Optional settings
PURRIO_API_URL=https://api.hyperliquid.xyz  # or testnet URL
PURRIO_OUTPUT_FORMAT=table     # table, json, or csv
PURRIO_NETWORK=mainnet         # mainnet or testnet
```

### Security Note

⚠️ **Never commit your private key to version control!** Use environment variables or a secure `.env` file.

## Output Formats

Purrio supports three output formats controlled by the `--output` flag:

- **TABLE** (default): Human-readable tables with formatted data
- **JSON**: Raw SDK data for agents/scripts - exactly what Hyperliquid API returns
- **CSV**: Formatted data for spreadsheets (same as TABLE but comma-separated)

```bash
# Examples of different output formats
purrio price BTC                    # TABLE: $50,000.50
purrio price BTC --output json      # JSON: {"BTC": "50000.5"}
purrio price BTC --output csv       # CSV: Coin,Price\nBTC,"$50,000.50"
```

**For Developers**: JSON output always returns raw Hyperliquid SDK data with no transformations - perfect for building tools and agents.

## Commands

### Information Commands

#### `purrio price [COINS...]`
Get current mid prices for specified coins.

```bash
purrio price              # All coins
purrio price BTC ETH      # Specific coins
purrio price BTC --output json # Raw SDK data
```

#### `purrio positions [ADDRESS]`
Get positions for any wallet address (defaults to configured address).

```bash
purrio positions 0x1234...
purrio positions 0x1234... --output json # Raw user_state data
```

#### `purrio orders [ADDRESS]`
Get open orders for any wallet address (defaults to configured address).

```bash
purrio orders 0x1234...
```

#### `purrio account [ADDRESS]`
Get account summary including balances and margin.

```bash
purrio account 0x1234...
```

#### `purrio funding COIN --hours N`
Get funding rate history for a coin.

```bash
purrio funding BTC           # Last 24 hours
purrio funding ETH --hours 48
```

#### `purrio orderbook COIN --depth N`
Get L2 orderbook snapshot.

```bash
purrio orderbook BTC          # Default 10 levels
purrio orderbook ETH --depth 20
```

#### `purrio fills [ADDRESS]`
Get recent trade fills for any address (defaults to configured address).

```bash
purrio fills 0x1234...
```

#### `purrio meta COIN`
Get asset metadata including max leverage and decimals.

```bash
purrio meta BTC
purrio meta @107     # Query by token ID
```

#### `purrio asset-ctx [COIN]`
Get asset metadata with market context (volume, funding, open interest).

```bash
purrio asset-ctx           # All assets
purrio asset-ctx BTC       # Single asset context
purrio asset-ctx --output json # Raw meta_and_asset_ctxs data
```

### Position Trading Commands

#### `purrio long COIN LEVERAGE MARGIN`
Open a long position with specified leverage and margin.

```bash
purrio long BTC 5x 1000      # 5x leverage, $1000 margin
purrio long ETH 10 2000      # 10x leverage, $2000 margin
purrio long SOL 3x 500 --slippage 2.0   # Custom slippage
```

Options:
- `--slippage`: Maximum slippage percentage (default: 1%)

#### `purrio short COIN LEVERAGE MARGIN`
Open a short position with specified leverage and margin.

```bash
purrio short BTC 3x 1500     # 3x leverage, $1500 margin
purrio short ETH 5x 1000     # 5x leverage, $1000 margin
purrio short SOL 2x 800 --slippage 1.5  # Custom slippage
```

Options:
- `--slippage`: Maximum slippage percentage (default: 1%)

#### `purrio close COIN PERCENTAGE`
Close a percentage of an existing position.

```bash
purrio close BTC 100%        # Close entire BTC position
purrio close ETH 50%         # Close half of ETH position
purrio close SOL 25          # Close 25% (% symbol optional)
```

#### `purrio close all PERCENTAGE`
Close a percentage of all open positions.

```bash
purrio close all 100%        # Close all positions completely
purrio close all 30%         # Take 30% profits on all positions
purrio close all 50 --slippage 2.0  # Custom slippage
```

Options:
- `--slippage`: Maximum slippage percentage (default: 1%)

### Limit Order Commands

#### `purrio limit long/short COIN LEVERAGE PRICE MARGIN`
Place a limit order with leverage and margin.

```bash
purrio limit long BTC 5x 50000 1000     # Long BTC at $50k, 5x leverage, $1000 margin
purrio limit short ETH 3x 3000 2000     # Short ETH at $3k, 3x leverage, $2000 margin
purrio limit long SOL 10x 100 500 --tif Ioc --reduce-only
```

Options:
- `--tif`: Time in force (Gtc, Ioc, Alo)
- `--reduce-only`: Reduce-only order

#### `purrio limit cancel COIN ORDER_ID`
Cancel an open order.

```bash
purrio limit cancel BTC 12345     # Cancel specific order
purrio limit cancel BTC --all     # Cancel all BTC orders
```

### Configuration Commands

#### `purrio config show`
Display current configuration.

```bash
purrio config show
purrio config show --output json
```

#### `purrio version`
Show CLI version.

```bash
purrio version
```

## Performance & Caching

Purrio includes intelligent caching to optimize performance:

### Asset Data Caching

Asset information (max leverage, decimals, names) is cached locally to avoid redundant API calls:

```bash
# Instant lookups using cached data
purrio asset ETH           # Shows max leverage, decimals
purrio asset @107          # Resolves token ID to name (ALT)

# Refresh asset cache when needed
purrio-refresh-assets           # Updates cached asset data
```

### Performance Benefits

- **Asset info lookups**: 100-1000x faster (cached vs API)
- **Leverage validation**: Instant for known assets
- **Token name resolution**: Instant for @ tokens
- **Commands affected**: `info asset`, leverage validation, @ token display

### Cache Management

The cache is automatically used but can be refreshed:

```bash
# Refresh cache (run occasionally)
poetry run purrio-refresh-assets

# Or manually
python scripts/refresh_assets.py
```

Cache files are stored in `src/purrio/constants/assets.py` and include both mainnet and testnet data.

## Agent Integration

Purrio is designed for programmatic use by agents and scripts:

### Python Example

```python
import subprocess
import json

# Get prices programmatically
result = subprocess.run(
    ["purrio", "--output", "json", "price", "BTC"],
    capture_output=True,
    text=True
)
data = json.loads(result.stdout)
btc_price = data["BTC"]
print(f"BTC Price: ${btc_price:,.2f}")

# Check positions
result = subprocess.run(
    ["purrio", "--output", "json", "positions", "0x..."],
    capture_output=True,
    text=True
)
positions = json.loads(result.stdout)
```

### Shell Script Example

```bash
#!/bin/bash

# Get BTC price
BTC_PRICE=$(purrio --output json price BTC | jq '.BTC')
echo "Current BTC price: $BTC_PRICE"

# Check if price is above threshold
if (( $(echo "$BTC_PRICE > 50000" | bc -l) )); then
    echo "BTC is above $50,000"
fi
```

### Design Principles for Agents

1. **No Interactive Prompts**: All input via flags/arguments
2. **Structured Output**: Consistent JSON schema
3. **Predictable Errors**: Clear error codes and messages
4. **Exit Codes**: 0 for success, 1 for error
5. **Idempotent Operations**: Safe for retry logic

## Output Formats

### Table (Default)
Human-readable format with Rich formatting:

```
┏━━━━━━━┳━━━━━━━━━━━━━┓
┃ Coin  ┃ Price       ┃
┡━━━━━━━╇━━━━━━━━━━━━━┩
│ BTC   │ $50,000.00  │
│ ETH   │ $3,000.00   │
└───────┴─────────────┘
```

### JSON
Machine-readable format for scripts:

```json
{
  "BTC": 50000.0,
  "ETH": 3000.0
}
```

### CSV
Spreadsheet-compatible format:

```csv
Coin,Price
BTC,50000.0
ETH,3000.0
```

## Development

### Project Structure

```
src/purrio/
├── cli.py              # Main application entry point
├── commands/           # Command modules
│   ├── base.py        # Shared decorators and utilities
│   ├── market.py      # Market operations (long, short, close)
│   ├── orders.py      # Limit orders and cancellation
│   ├── query.py       # Account queries (positions, orders, fills)
│   ├── data.py        # Market data (prices, funding, orderbook)
│   └── config.py      # Configuration commands
├── client.py          # Hyperliquid SDK wrapper
├── config.py          # Configuration management (Pydantic models)
├── constants/         # Static data
│   └── assets.py      # Cached asset information
├── context.py         # Application context
├── output.py          # Output formatting (table/json/csv)
├── types.py           # Type definitions
└── utils.py           # Shared utilities
```

### Setup

```bash
# Clone repository
git clone https://github.com/purrio/purrio-cli.git
cd purrio-cli

# Install dependencies
poetry install

# Install pre-commit hooks
pre-commit install
```

### Testing

```bash
# Run tests
poetry run pytest

# Run with coverage
poetry run pytest --cov

# Run specific test
poetry run pytest tests/test_config.py
```

### Code Quality

```bash
# Format code
poetry run ruff format

# Lint code
poetry run ruff check --fix

# Type checking
poetry run mypy src/
```

## Known Issues

1. **Python 3.11+ Compatibility**: The `parsimonious` library (dependency of eth-abi) has issues with Python 3.11+. Currently recommended to use Python 3.10.

## Support

- GitHub Issues: [github.com/purrio/purrio-cli/issues](https://github.com/purrio/purrio-cli/issues)
- Documentation: [docs.purrio.io](https://docs.purrio.io)

## License

MIT License - see LICENSE file for details.

## Disclaimer

This software is provided "as is" without warranty of any kind. Trading cryptocurrencies carries risk. Always verify orders and positions through official Hyperliquid interfaces.
