hyperliquid-monitor


Namehyperliquid-monitor JSON
Version 0.1.2.1 PyPI version JSON
download
home_pagehttps://github.com/oni-giri/hyperliquid-monitor
SummaryA Hyperliquid trade monitor package
upload_time2024-11-08 22:28:49
maintainerNone
docs_urlNone
authorYakitori
requires_python<4.0,>=3.9
licenseMIT
keywords hyperliquid trading cryptocurrency monitor dex
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![image](https://github.com/Oni-giri/hyperliquid-monitor/blob/main/assets/head-image.png?raw=true)

# Hyperliquid Monitor

A Python package for monitoring trades and orders on Hyperliquid DEX in real-time. This package allows you to track specific addresses and receive notifications when trades are executed or orders are placed/cancelled.

## Features

- Real-time monitoring of trades and orders
- Support for multiple addresses
- Optional SQLite database storage
- Callback system for custom notifications
- Clean shutdown handling
- Proper trade type definitions using dataclasses

## Installation

### Using Poetry (recommended)

```bash
poetry add hyperliquid-monitor
```

### Using pip

```bash
pip install hyperliquid-monitor
```

## Quick Start

### Simple Console Notification

Here's a basic example that monitors an address and prints trades to the console:

```python
from hyperliquid_monitor import HyperliquidMonitor
from hyperliquid_monitor.types import Trade
from datetime import datetime

def print_trade(trade: Trade):
    """Print trade information to console with colors"""
    timestamp = trade.timestamp.strftime('%Y-%m-%d %H:%M:%S')
    
    # Color codes
    GREEN = '\033[92m'
    RED = '\033[91m'
    BLUE = '\033[94m'
    RESET = '\033[0m'
    
    # Choose color based on trade type and side
    color = GREEN if trade.side == "BUY" else RED
    
    print(f"\n{BLUE}[{timestamp}]{RESET} New {trade.trade_type}:")
    print(f"Address: {trade.address}")
    print(f"Coin: {trade.coin}")
    print(f"{color}Side: {trade.side}{RESET}")
    print(f"Size: {trade.size}")
    print(f"Price: {trade.price}")
    
    if trade.trade_type == "FILL":
        print(f"Direction: {trade.direction}")
        if trade.closed_pnl:
            pnl_color = GREEN if trade.closed_pnl > 0 else RED
            print(f"PnL: {pnl_color}{trade.closed_pnl:.2f}{RESET}")
        print(f"Hash: {trade.tx_hash}")

def main():
    # List of addresses to monitor
    addresses = [
        "0x010461C14e146ac35Fe42271BDC1134EE31C703a"  # Example address
    ]

    # Create monitor with console notifications and optional database
    monitor = HyperliquidMonitor(
        addresses=addresses,
        db_path="trades.db",  # Optional: remove to disable database
        callback=print_trade
    )

    try:
        print("Starting monitor... Press Ctrl+C to exit")
        monitor.start()
    except KeyboardInterrupt:
        monitor.stop()

if __name__ == "__main__":
    main()
```

### Trade Object Structure

The `Trade` object contains the following information:

```python
@dataclass
class Trade:
    timestamp: datetime      # When the trade occurred
    address: str            # The address that made the trade
    coin: str              # The traded coin/token
    side: Literal["BUY", "SELL"]  # Trade side
    size: float            # Trade size
    price: float           # Trade price
    trade_type: Literal["FILL", "ORDER_PLACED", "ORDER_CANCELLED"]
    direction: Optional[str] = None  # e.g., "Open Long", "Close Short"
    tx_hash: Optional[str] = None    # Transaction hash for fills
    fee: Optional[float] = None      # Trading fee
    fee_token: Optional[str] = None  # Fee token (e.g., "USDC")
    start_position: Optional[float] = None  # Position size before trade
    closed_pnl: Optional[float] = None     # Realized PnL for closing trades
    order_id: Optional[int] = None         # Order ID for orders
```

## Database Storage

If you provide a `db_path`, trades will be stored in an SQLite database with two tables:

### Fills Table
- timestamp: When the trade occurred
- address: Trader's address
- coin: Traded asset
- side: BUY/SELL
- size: Trade size
- price: Trade price
- direction: Trade direction
- tx_hash: Transaction hash
- fee: Trading fee
- fee_token: Fee token
- start_position: Position before trade
- closed_pnl: Realized PnL

### Orders Table
- timestamp: When the order was placed/cancelled
- address: Trader's address
- coin: Asset
- action: placed/cancelled
- side: BUY/SELL
- size: Order size
- price: Order price
- order_id: Unique order ID

## Database Recording Modes

The monitor supports different modes of operation for recording trades:

### 1. Full Monitoring with Notifications
```python
# Records to database and sends notifications via callback
monitor = HyperliquidMonitor(
    addresses=addresses,
    db_path="trades.db",
    callback=print_trade
)
```

### 2. Silent Database Recording
```python
# Only records to database, no notifications
monitor = HyperliquidMonitor(
    addresses=addresses,
    db_path="trades.db",
    silent=True  # Suppresses all notifications and console output
)
```

### 3. Notification-Only Mode
```python
# Only sends notifications, no database recording
monitor = HyperliquidMonitor(
    addresses=addresses,
    callback=print_trade
)
```

The silent mode is particularly useful for:
- Background monitoring and data collection
- Reducing system resource usage
- Running multiple monitors concurrently
- Long-term trade data accumulation
- Server-side deployments where notifications aren't needed

Note: Silent mode requires a database path to be specified since it's meant for data recording.

## Development

### Setting up the Development Environment

1. Clone the repository:
```bash
git clone https://github.com/your-username/hyperliquid-monitor.git
cd hyperliquid-monitor
```

2. Install poetry if you haven't already:
```bash
curl -sSL https://install.python-poetry.org | python3 -
```

3. Install dependencies:
```bash
poetry install
```

### Running Tests

The package includes a comprehensive test suite using pytest. To run the tests:

```bash
# Run all tests
poetry run pytest

# Run with coverage report
poetry run pytest --cov

# Run specific test file
poetry run pytest tests/test_monitor.py

# Run tests with output
poetry run pytest -v
```

### Test Structure

Tests are organized in the following structure:
```
tests/
├── __init__.py
├── conftest.py          # Shared fixtures
├── test_monitor.py      # Monitor tests
├── test_database.py     # Database tests
└── test_types.py        # Type validation tests
```

Key test areas:
- Monitor functionality (subscriptions, event handling)
- Database operations (storage, retrieval)
- Type validation (trade object validation)
- Event processing (fills, orders)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. Make sure to:

1. Add tests for any new functionality
2. Update documentation as needed
3. Follow the existing code style
4. Run the test suite before submitting

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Acknowledgments

Built on top of the official Hyperliquid Python SDK
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/oni-giri/hyperliquid-monitor",
    "name": "hyperliquid-monitor",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.9",
    "maintainer_email": null,
    "keywords": "hyperliquid, trading, cryptocurrency, monitor, dex",
    "author": "Yakitori",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/46/3e/79c9f6f646c82f0d3f0689dbb02e2a413b3f622d860964c7acddb19ca617/hyperliquid_monitor-0.1.2.1.tar.gz",
    "platform": null,
    "description": "![image](https://github.com/Oni-giri/hyperliquid-monitor/blob/main/assets/head-image.png?raw=true)\n\n# Hyperliquid Monitor\n\nA Python package for monitoring trades and orders on Hyperliquid DEX in real-time. This package allows you to track specific addresses and receive notifications when trades are executed or orders are placed/cancelled.\n\n## Features\n\n- Real-time monitoring of trades and orders\n- Support for multiple addresses\n- Optional SQLite database storage\n- Callback system for custom notifications\n- Clean shutdown handling\n- Proper trade type definitions using dataclasses\n\n## Installation\n\n### Using Poetry (recommended)\n\n```bash\npoetry add hyperliquid-monitor\n```\n\n### Using pip\n\n```bash\npip install hyperliquid-monitor\n```\n\n## Quick Start\n\n### Simple Console Notification\n\nHere's a basic example that monitors an address and prints trades to the console:\n\n```python\nfrom hyperliquid_monitor import HyperliquidMonitor\nfrom hyperliquid_monitor.types import Trade\nfrom datetime import datetime\n\ndef print_trade(trade: Trade):\n    \"\"\"Print trade information to console with colors\"\"\"\n    timestamp = trade.timestamp.strftime('%Y-%m-%d %H:%M:%S')\n    \n    # Color codes\n    GREEN = '\\033[92m'\n    RED = '\\033[91m'\n    BLUE = '\\033[94m'\n    RESET = '\\033[0m'\n    \n    # Choose color based on trade type and side\n    color = GREEN if trade.side == \"BUY\" else RED\n    \n    print(f\"\\n{BLUE}[{timestamp}]{RESET} New {trade.trade_type}:\")\n    print(f\"Address: {trade.address}\")\n    print(f\"Coin: {trade.coin}\")\n    print(f\"{color}Side: {trade.side}{RESET}\")\n    print(f\"Size: {trade.size}\")\n    print(f\"Price: {trade.price}\")\n    \n    if trade.trade_type == \"FILL\":\n        print(f\"Direction: {trade.direction}\")\n        if trade.closed_pnl:\n            pnl_color = GREEN if trade.closed_pnl > 0 else RED\n            print(f\"PnL: {pnl_color}{trade.closed_pnl:.2f}{RESET}\")\n        print(f\"Hash: {trade.tx_hash}\")\n\ndef main():\n    # List of addresses to monitor\n    addresses = [\n        \"0x010461C14e146ac35Fe42271BDC1134EE31C703a\"  # Example address\n    ]\n\n    # Create monitor with console notifications and optional database\n    monitor = HyperliquidMonitor(\n        addresses=addresses,\n        db_path=\"trades.db\",  # Optional: remove to disable database\n        callback=print_trade\n    )\n\n    try:\n        print(\"Starting monitor... Press Ctrl+C to exit\")\n        monitor.start()\n    except KeyboardInterrupt:\n        monitor.stop()\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### Trade Object Structure\n\nThe `Trade` object contains the following information:\n\n```python\n@dataclass\nclass Trade:\n    timestamp: datetime      # When the trade occurred\n    address: str            # The address that made the trade\n    coin: str              # The traded coin/token\n    side: Literal[\"BUY\", \"SELL\"]  # Trade side\n    size: float            # Trade size\n    price: float           # Trade price\n    trade_type: Literal[\"FILL\", \"ORDER_PLACED\", \"ORDER_CANCELLED\"]\n    direction: Optional[str] = None  # e.g., \"Open Long\", \"Close Short\"\n    tx_hash: Optional[str] = None    # Transaction hash for fills\n    fee: Optional[float] = None      # Trading fee\n    fee_token: Optional[str] = None  # Fee token (e.g., \"USDC\")\n    start_position: Optional[float] = None  # Position size before trade\n    closed_pnl: Optional[float] = None     # Realized PnL for closing trades\n    order_id: Optional[int] = None         # Order ID for orders\n```\n\n## Database Storage\n\nIf you provide a `db_path`, trades will be stored in an SQLite database with two tables:\n\n### Fills Table\n- timestamp: When the trade occurred\n- address: Trader's address\n- coin: Traded asset\n- side: BUY/SELL\n- size: Trade size\n- price: Trade price\n- direction: Trade direction\n- tx_hash: Transaction hash\n- fee: Trading fee\n- fee_token: Fee token\n- start_position: Position before trade\n- closed_pnl: Realized PnL\n\n### Orders Table\n- timestamp: When the order was placed/cancelled\n- address: Trader's address\n- coin: Asset\n- action: placed/cancelled\n- side: BUY/SELL\n- size: Order size\n- price: Order price\n- order_id: Unique order ID\n\n## Database Recording Modes\n\nThe monitor supports different modes of operation for recording trades:\n\n### 1. Full Monitoring with Notifications\n```python\n# Records to database and sends notifications via callback\nmonitor = HyperliquidMonitor(\n    addresses=addresses,\n    db_path=\"trades.db\",\n    callback=print_trade\n)\n```\n\n### 2. Silent Database Recording\n```python\n# Only records to database, no notifications\nmonitor = HyperliquidMonitor(\n    addresses=addresses,\n    db_path=\"trades.db\",\n    silent=True  # Suppresses all notifications and console output\n)\n```\n\n### 3. Notification-Only Mode\n```python\n# Only sends notifications, no database recording\nmonitor = HyperliquidMonitor(\n    addresses=addresses,\n    callback=print_trade\n)\n```\n\nThe silent mode is particularly useful for:\n- Background monitoring and data collection\n- Reducing system resource usage\n- Running multiple monitors concurrently\n- Long-term trade data accumulation\n- Server-side deployments where notifications aren't needed\n\nNote: Silent mode requires a database path to be specified since it's meant for data recording.\n\n## Development\n\n### Setting up the Development Environment\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/your-username/hyperliquid-monitor.git\ncd hyperliquid-monitor\n```\n\n2. Install poetry if you haven't already:\n```bash\ncurl -sSL https://install.python-poetry.org | python3 -\n```\n\n3. Install dependencies:\n```bash\npoetry install\n```\n\n### Running Tests\n\nThe package includes a comprehensive test suite using pytest. To run the tests:\n\n```bash\n# Run all tests\npoetry run pytest\n\n# Run with coverage report\npoetry run pytest --cov\n\n# Run specific test file\npoetry run pytest tests/test_monitor.py\n\n# Run tests with output\npoetry run pytest -v\n```\n\n### Test Structure\n\nTests are organized in the following structure:\n```\ntests/\n\u251c\u2500\u2500 __init__.py\n\u251c\u2500\u2500 conftest.py          # Shared fixtures\n\u251c\u2500\u2500 test_monitor.py      # Monitor tests\n\u251c\u2500\u2500 test_database.py     # Database tests\n\u2514\u2500\u2500 test_types.py        # Type validation tests\n```\n\nKey test areas:\n- Monitor functionality (subscriptions, event handling)\n- Database operations (storage, retrieval)\n- Type validation (trade object validation)\n- Event processing (fills, orders)\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request. Make sure to:\n\n1. Add tests for any new functionality\n2. Update documentation as needed\n3. Follow the existing code style\n4. Run the test suite before submitting\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Acknowledgments\n\nBuilt on top of the official Hyperliquid Python SDK",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Hyperliquid trade monitor package",
    "version": "0.1.2.1",
    "project_urls": {
        "Homepage": "https://github.com/oni-giri/hyperliquid-monitor",
        "Repository": "https://github.com/oni-giri/hyperliquid-monitor"
    },
    "split_keywords": [
        "hyperliquid",
        " trading",
        " cryptocurrency",
        " monitor",
        " dex"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "047858c676488a0083e27b11593826385ac05834cc53b5ce666a9c7e59f6919d",
                "md5": "fff761ba78077bdaed5ec864de589c6a",
                "sha256": "465feceb0fad56fe04cce3c124ff12839194dac3d08d7eb34342529a402dd540"
            },
            "downloads": -1,
            "filename": "hyperliquid_monitor-0.1.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fff761ba78077bdaed5ec864de589c6a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.9",
            "size": 9659,
            "upload_time": "2024-11-08T22:28:47",
            "upload_time_iso_8601": "2024-11-08T22:28:47.624992Z",
            "url": "https://files.pythonhosted.org/packages/04/78/58c676488a0083e27b11593826385ac05834cc53b5ce666a9c7e59f6919d/hyperliquid_monitor-0.1.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "463e79c9f6f646c82f0d3f0689dbb02e2a413b3f622d860964c7acddb19ca617",
                "md5": "01a32eb3b3e541aa2505396c7761319e",
                "sha256": "9001d8542a5233e40b9580b14b302003ce0b25ecbec3f7f343e36f0a6fb489bc"
            },
            "downloads": -1,
            "filename": "hyperliquid_monitor-0.1.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "01a32eb3b3e541aa2505396c7761319e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.9",
            "size": 10112,
            "upload_time": "2024-11-08T22:28:49",
            "upload_time_iso_8601": "2024-11-08T22:28:49.232380Z",
            "url": "https://files.pythonhosted.org/packages/46/3e/79c9f6f646c82f0d3f0689dbb02e2a413b3f622d860964c7acddb19ca617/hyperliquid_monitor-0.1.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-08 22:28:49",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "oni-giri",
    "github_project": "hyperliquid-monitor",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "hyperliquid-monitor"
}
        
Elapsed time: 0.40732s