Skip to content

High-Performance Market-Neutral Arbitrage Bot for Drift Protocol & Hyperliquid Perpetuals

License

Notifications You must be signed in to change notification settings

rustjesty/hyperliquid-drift-arbitrage-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hyperliquid ↔ Drift Arbitrage Bot

Project Overview

Drift-Hyperliquid Arbitrage Bot is a professional-grade, modular trading platform designed for automated arbitrage across Drift (Solana) and Hyperliquid perpetual markets. Built with reliability and extensibility in mind, this system continuously monitors both exchanges to identify lucrative price and funding rate discrepancies, and executes fully hedged trades to capture market-neutral profit opportunities.

Key features include:

  • Rapid, asynchronous order execution for minimized risk
  • Atomic transaction handling across both venues
  • Strategy pluggability for basis and funding arbitrage
  • Robust simulation and live-trading modes
  • Typed, environment-secure configuration

Whether you're pursuing institutional research, seeking safe automation for live trading, or simply exploring advanced crypto arbitrage techniques, this project provides a strong, scalable foundation for modern cross-exchange trading operations.

Key Features & Architecture

  • Modular Connector Framework: All exchange interactions are abstracted through a unified ConnectorBase layer, providing asynchronous access to market data, funding rates, and order management interfaces.
  • Atomic Execution Engine: The ExecutionEngine manages paired order placement across exchanges. Orders are submitted atomically and rolled back if either leg fails to fill, minimizing directional risk.
  • Pluggable Strategy Layer: Dedicated strategy modules implement both basis and funding arbitrage logic, leveraging shared connectors and execution mechanisms.
  • Typed Configuration Loader: Uses Pydantic for strict config validation and automatic environment variable overrides for sensitive information.
  • Unified CLI Runner: Launches single or multiple strategies concurrently via a consolidated CLI entrypoint.
  • End-to-End Testing: Comprehensive Pytest suite ensures integrity across connectors, strategies, and execution logic.

Supported Strategies

Basis Arbitrage

  • Compares spot-equivalent prices of perpetual contracts across both venues.
  • Evaluates the average execution price (to account for slippage) based on order book depth for the configured amount.
  • Net profit is calculated after subtracting expected taker fees and accounting for slippage.
  • Trades are triggered only if projected returns exceed both the min_profit_usd threshold and respect the max_slippage_bps limit.
  • The position (long/short) is allocated to the venue with the higher calculated net profit.

Funding Rate Arbitrage

  • Assesses the spread between expected funding payments on Drift and Hyperliquid.
  • Uses current order books and funding rates, factoring in mid prices and position size.
  • The arbitrage opportunity is calculated for a given holding period (hold_time_sec), net of all entry/exit fees and slippage.
  • Trades are executed market-neutrally: long on the exchange with lower projected funding costs, short on the higher.

Both strategies utilize order book snapshots and funding data via connectors. Strategy signals are passed to the ExecutionEngine, which handles synchronized execution with compliance checks for slippage and fill timeouts.

Installation & Setup

  1. Install Python: Requires Python 3.12 or later.
  2. Create a virtual environment (recommended):
    python -m venv .venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  3. Install dependencies:
    pip install -r requirements.txt
  4. Configure the bot:
    • Copy the default configuration:
      cp config/main.example.yaml config/main.yaml
    • Edit config/main.yaml as required. Never commit secrets; use environment variables for keys and credentials.

Running the Bot

Invoke the CLI to start the desired strategy in either live or dry-run mode:

python cli.py --strategy basis --mode live --config config/main.yaml

Main options:

  • --strategy {basis,funding} – Specify the strategy module. Omit to run all enabled strategies concurrently.
  • --mode {live,dry-run} or --dry-run – Toggle between live trading and simulation modes.
  • --safe-mode – Enforce a no-trade (safe) mode, blocking new trade attempts until re-enabled.

Required Environment Variables

Sensitive credentials are automatically loaded from environment variables if omitted from YAML config:

  • DRIFT_PRIVATE_KEY
  • HYPERLIQUID_API_KEY
  • HYPERLIQUID_API_SECRET
  • HYPERLIQUID_ACCOUNT_ADDRESS

Logging and Monitoring

  • Streamed logs are output to console and, optionally, to persistent log files.
  • Executed trades and found arbitrage opportunities are stored in JSONL format:
    • storage/trades.jsonl
    • storage/opportunities.jsonl
    • storage/events.log

Execution Workflow & Risk Management

Process Summary

  • The bot records all open positions on both exchanges prior to each trade.
  • Long/short (hedged) orders are placed asynchronously; atomicity is strictly enforced by rolling back incomplete pairs.
  • Fills are monitored at 1-second intervals, with strict per-leg timeouts (default: 10 seconds).
  • Orders are marked successful only if both legs are confirmed filled within the timeout. Realized slippage for each leg is computed and logged.
  • If an order fails to fill or times out, unfilled legs are canceled, the incident is logged, and the bot enters safe mode requiring manual review before resuming trading.

Specific Risk Controls

  • Execution Delay: Fully asynchronous execution to minimize inter-leg latency with enforced timeouts.
  • Slippage Control: Expected versus realized price is checked and flagged if above max_slippage_bps.
  • Partial Fill Prevention: Incomplete pairs are rolled back and the bot auto-restricts further orders pending review.
  • Exception Handling: SDK, network, and API errors are comprehensively caught and managed; all critical incidents are logged.
  • Comprehensive Audit Trail: Full parameters and execution outcomes are logged for audit and incident investigation.

Notable External/Emergent Risks

  • Settlement (blockchain/L2) delays beyond trading engine control.
  • Order book movement and volatility between signal and execution.
  • Exchange API downtime, failure, or undocumented parameter changes.
  • Data lags or desyncs between SDK and actual exchange state can cause execution discrepancies.

All operations must be continually monitored during live trading. Manual intervention is advised for all production deployments.

Security Best Practices

  • Do not commit secrets: The repository's .gitignore already excludes config/main.yaml and .env files from source control.
  • Always inject secrets via environment variables when possible.
  • Use least-privilege API/account permissions and consider using non-primary accounts for trading bots.

License & Disclaimer

This project is provided under the MIT License and is intended strictly for research and development purposes. Operating the bot with real funds is highly discouraged without a comprehensive external security audit. You use this software entirely at your own risk; no warranty is provided.

Support

For technical support, questions, or to discuss development, please reach out via the official Telegram channel:

Telegram

About

High-Performance Market-Neutral Arbitrage Bot for Drift Protocol & Hyperliquid Perpetuals

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages