Skip to content

baties/Hyperliquid-Delta_Neutral-TBot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hyperliquid Delta-Neutral Maker Bot

Python 3.9+ License: MIT Contributions Welcome

An open-source delta-neutral market making bot for Hyperliquid — a high-performance on-chain perpetual exchange. The bot earns maker rebates by placing one-sided limit orders and immediately hedging every fill, maintaining a near-zero directional exposure at all times.

Disclaimer: This software is provided for educational and research purposes. Trading cryptocurrency derivatives involves substantial risk of loss. Use at your own risk. See Disclaimer for full details.


Table of Contents


How It Works

The bot implements a delta-neutral market making strategy with four core mechanics:

1. One-Sided Quoting

Unlike traditional market makers that quote both sides of the book simultaneously, this bot quotes only one side at a time (buy-only or sell-only). This halves inventory risk while still earning maker rebates on every filled order.

2. Immediate Delta Hedging

Every time a maker order fills, the bot instantly places an opposite hedge order to flatten the position. The hedge uses a tiered approach:

Tier Method When
Tier 1 Post-only limit order (earns rebate) Default — best economics
Tier 2 Aggressive limit order If Tier 1 fails or times out
Tier 3 Emergency market order Last resort — pays taker fee

3. Rebate Harvesting

Hyperliquid pays a maker rebate (~0.03 bps) on every filled limit order. By generating high volume while staying delta-neutral, the bot compounds these micro-rebates into consistent returns.

Daily Volume    × Rebate Rate  = Daily Rebates
$10,000         × 0.003%       = $0.30
$100,000        × 0.003%       = $3.00
$1,000,000      × 0.003%       = $30.00

4. Dynamic Side Switching

The bot switches between buy-only and sell-only phases based on configurable triggers:

  • Volume target reached on the current side
  • Time limit exceeded on the current side
  • Risk threshold crossed (position growing too directional)

Features

  • Delta-neutral execution — immediate hedge on every fill keeps net exposure near zero
  • Tiered hedge system — graceful degradation from post-only → aggressive → emergency market
  • Multi-layer risk management — drawdown limits, position caps, daily loss limits, margin monitoring, and auto-deleverage
  • Telegram integration — real-time notifications, status commands, and remote bot control
  • WebSocket price feed — low-latency market data via Hyperliquid WebSocket API
  • Rich console dashboard — live PnL, positions, volume, risk metrics in your terminal
  • Post-only order mode — ensures all maker orders earn rebates (never accidentally taker)
  • Configurable via YAML — no code changes needed to adjust strategy parameters
  • Testnet support — full functionality on Hyperliquid testnet for risk-free development

Architecture

┌──────────────────────────────────────────────────────────────┐
│                        main.py (CLI)                         │
│              Entry point · Arg parsing · Safety checks       │
└──────────────┬───────────────────────────────────┬───────────┘
               │                                   │
    ┌──────────▼──────────┐             ┌──────────▼──────────┐
    │  DeltaNeutralMaker  │             │   StatusMonitor      │
    │  Bot (maker_bot.py) │             │   (monitor.py)       │
    │                     │             │                      │
    │  • Trading loop     │             │  • Live dashboard    │
    │  • Side switching   │             │  • PnL tracking      │
    │  • Fill detection   │             │  • Risk alerts       │
    │  • Hedge execution  │             └──────────────────────┘
    └──────┬────────┬─────┘
           │        │
  ┌────────▼──┐  ┌──▼──────────────┐
  │ Hyperliquid│  │  RiskManager    │
  │ Client     │  │ (risk_manager)  │
  │            │  │                 │
  │ • Orders   │  │ • Drawdown     │
  │ • Positions│  │ • Position cap │
  │ • Balances │  │ • Daily limits │
  │ • Leverage │  │ • Margin guard │
  └────────┬───┘  └────────────────┘
           │
  ┌────────▼───────────┐     ┌──────────────────┐
  │  WebSocket Monitor │     │  Telegram Bot     │
  │ (websocket_monitor)│     │  (telegram.py)    │
  │                    │     │                   │
  │ • Real-time prices │     │ • Notifications   │
  │ • Fill events      │     │ • Status commands │
  └────────────────────┘     └──────────────────┘

For a detailed Mermaid flowchart of the trading loop, see Documents/flowchart.md.


Prerequisites

Requirement Details
Python 3.9 or higher
Hyperliquid account Create one here
API wallet Generate an API agent wallet from the Hyperliquid dashboard
RPC endpoint (optional) Your own node or a provider like Chainstack for lower latency
Telegram bot (optional) Create via @BotFather for notifications

Installation

# 1. Clone the repository
git clone https://github.com/<your-username>/Hyperliquid-Delta_Neutral-TBot.git
cd Hyperliquid-Delta_Neutral-TBot

# 2. Create and activate a virtual environment
python -m venv venv
source venv/bin/activate   # macOS / Linux
# venv\Scripts\activate    # Windows

# 3. Install dependencies
pip install -r requirements.txt

# 4. Set up environment variables
cp .env.example .env
# Edit .env with your wallet keys and RPC endpoints (see Configuration below)

Configuration

Environment Variables (.env)

Copy .env.example to .env and fill in your values:

# Your main trading wallet address
MAIN_WALLET_ADDRESS=0xYourMainWalletAddressHere

# API agent wallet private key (for signing orders)
WALLET_PRIVATE_KEY=your_wallet_private_key_here

# Network: testnet or mainnet
NETWORK=testnet

# RPC endpoints (optional — defaults to public Hyperliquid endpoints)
CHAINSTACK_MAINNET_BASE_URL=https://hyperliquid-mainnet.core.chainstack.com/YOUR_PROJECT_ID
CHAINSTACK_MAINNET_INFO_URL=https://hyperliquid-mainnet.core.chainstack.com/YOUR_PROJECT_ID/info
CHAINSTACK_MAINNET_WS_URL=wss://hyperliquid-mainnet.core.chainstack.com/ws/YOUR_PROJECT_ID

Never commit your .env file. It is already in .gitignore.

Strategy Parameters (config.yaml)

All trading parameters live in config.yaml. A conservative starter config is provided in config-small.yaml for accounts with $100–200.

Section Key Parameters
trading symbol, max_position_size, order_size, min_spread_bps, use_post_only
risk max_drawdown, emergency_stop_loss, max_daily_loss, max_leverage, hedge_timeout
bot cycle_delay, side_switch_volume, side_switch_time
monitoring status_update_interval, balance_check_interval
Example: Small Balance Config ($100–200)
trading:
  symbol: "BTC-USD"
  max_position_size: 150
  order_size: 50
  target_daily_volume: 500
  min_spread_bps: 0.2
  min_size: 25
  use_post_only: true

risk:
  max_drawdown: 0.20
  emergency_stop_loss: 0.04
  max_daily_loss: 20
  max_leverage: 10
  hedge_timeout: 2

bot:
  cycle_delay: 0.1
  side_switch_volume: 200
  side_switch_time: 300
Example: Medium Balance Config ($1,000+)
trading:
  symbol: "BTC-USD"
  max_position_size: 10000
  order_size: 1000
  target_daily_volume: 100000
  min_spread_bps: 0.2
  min_size: 25
  use_post_only: true

risk:
  max_drawdown: 0.05
  emergency_stop_loss: 0.10
  max_daily_loss: 100
  max_leverage: 5
  hedge_timeout: 2

bot:
  cycle_delay: 0.05
  side_switch_volume: 50000
  side_switch_time: 600

Usage

Test Connection

Always verify connectivity before running the bot:

python src/main.py --test-connection

Start on Testnet (Recommended First)

NETWORK=testnet python src/main.py --start --verbose

Start on Mainnet

NETWORK=mainnet python src/main.py --start

Console Dashboard

While running, the bot displays a live dashboard:

═══════════════════════════════════════════════════════════════
🤖 HYPERLIQUID MAKER BOT STATUS
═══════════════════════════════════════════════════════════════
Network: TESTNET | Runtime: 02:15:30

💰 Balance: $198.45 | PnL: -$1.55 (-0.78%)
📈 Position: SOL +0.023 ($2.34) | ETH -0.016 ($3.45)
📊 Volume: $1,234 | Trades: 28 | Est. Rebates: $0.37
⚠️  Utilization: 45.2% | Drawdown: 0.8%
═══════════════════════════════════════════════════════════════

Telegram Commands

If configured, the Telegram bot provides:

  • Status updates and PnL notifications
  • Remote monitoring of positions and risk metrics
  • Alert notifications on risk events

Risk Management

The bot implements four layers of protection that operate simultaneously:

Layer 1 — Position Limits
├── Max position size cap
├── Position utilization scaling (reduces order size as exposure grows)
└── Emergency position exit on extreme conditions

Layer 2 — Drawdown Protection
├── Real-time peak-to-trough monitoring
├── Automatic halt when drawdown limit hit
└── Consecutive loss streak detection

Layer 3 — Daily Limits
├── Daily loss cap (absolute USD)
├── Volume monitoring
└── Time-based daily reset

Layer 4 — Market Condition Filters
├── Minimum spread requirement for profitability
├── Volatility filters (avoid extreme conditions)
├── Liquidity depth checks
└── Margin maintenance guard with auto-deleverage

Project Structure

Hyperliquid-Delta_Neutral-TBot/
├── src/
│   ├── main.py                    # CLI entry point, arg parsing, safety checks
│   ├── bot/
│   │   └── telegram.py            # Telegram bot integration & notifications
│   ├── connect/
│   │   └── websocket_monitor.py   # WebSocket price feed & fill event listener
│   ├── exchange/
│   │   └── hyperliquid_client.py  # Hyperliquid API client (orders, positions, balances)
│   ├── monitoring/
│   │   └── monitor.py             # Live console dashboard & performance tracking
│   ├── trading/
│   │   ├── maker_bot.py           # Core trading engine (quoting, hedging, side switching)
│   │   └── risk_manager.py        # Multi-layer risk controls & position monitoring
│   └── utils/
│       └── utils.py               # Config loading, env validation, logging setup
├── Documents/
│   ├── flowchart.md               # Mermaid flowchart of the trading loop
│   └── sequence_diagram.md        # Sequence diagram of order lifecycle
├── config.yaml                    # Default strategy configuration
├── config-small.yaml              # Conservative config for small balances
├── .env.example                   # Environment variable template
├── requirements.txt               # Python dependencies
├── .gitignore
└── README.md

Contributing

Contributions are welcome! Whether it's bug fixes, new features, documentation improvements, or strategy ideas — all help is appreciated.

How to Contribute

  1. Fork the repository
  2. Create a feature branch:
    git checkout -b feature/your-feature-name
  3. Make your changes — keep commits focused and well-described
  4. Test thoroughly — especially on testnet before any trading logic changes
  5. Submit a Pull Request with a clear description of what changed and why

Contribution Ideas

Area Ideas
Strategy New side-switching heuristics, spread optimization, multi-symbol support
Risk Better drawdown recovery logic, correlation-aware position limits
Infrastructure Docker support, CI/CD pipeline, automated testnet testing
Monitoring Grafana dashboard integration, trade history export (CSV/JSON)
Documentation Strategy deep-dives, configuration guides, deployment tutorials
Testing Unit tests, integration tests, backtesting framework

Guidelines

  • Keep PRs small and focused — one feature or fix per PR
  • Don't commit .env files, logs, or any secrets
  • Test on testnet before submitting trading logic changes
  • Add comments explaining why, not just what
  • Update documentation if your change affects usage or configuration

Roadmap

  • Multi-symbol support (trade multiple pairs concurrently)
  • Docker Compose setup for one-command deployment
  • Backtesting engine with historical data replay
  • Web-based monitoring dashboard
  • Automated testnet CI testing
  • Advanced spread models (volatility-adjusted, inventory-aware)
  • Trade history export and analytics
  • Plugin system for custom strategies

FAQ

What exchange does this work with?

Only Hyperliquid — a fully on-chain perpetual futures exchange on its own L1 blockchain. The bot uses Hyperliquid's native API via the hyperliquid-python-sdk.

How much capital do I need?

You can start with as little as $100 on testnet (free). For mainnet, $100–200 is a reasonable starting point to understand the bot's behavior. Meaningful rebate income typically requires higher volume, which needs more capital or leverage.

Is this the same strategy that turned $6.8k into $1.5M?

This bot implements the same core concept (one-sided quoting + immediate delta hedging + rebate harvesting). However, the original result involved professional infrastructure, co-located servers, perfect market timing, and deep expertise. This is an educational open-source implementation — results will vary significantly.

Do I need my own RPC node?

No. The bot works with the default public Hyperliquid endpoints. However, for lower latency and higher reliability, you can configure a private RPC endpoint from providers like Chainstack or Alchemy.

Can I run this on a VPS / cloud server?

Yes. Any Linux VPS with Python 3.9+ works. A server with low latency to Hyperliquid's infrastructure will perform better. Ensure your .env file is secured with proper file permissions (chmod 600 .env).


Disclaimer

This software is provided "as is", without warranty of any kind, express or implied.

  • This bot trades with real funds on mainnet. You can lose some or all of your capital.
  • Past performance (including any referenced results) does not guarantee future results.
  • The authors and contributors are not responsible for any financial losses incurred.
  • This is not financial advice. Do your own research and consult a financial advisor.
  • You are solely responsible for complying with applicable laws and regulations in your jurisdiction.
  • Never risk more than you can afford to lose entirely.

Known Risks

Risk Category Description
Execution Bot failures, network latency, or exchange downtime can leave positions unhedged
Market Extreme volatility, liquidity gaps, or flash crashes can overwhelm hedging
Operational Private key compromise, misconfiguration, or unattended operation
Competition Professional HFT firms with superior infrastructure compete for the same rebates

License

This project is licensed under the MIT License.


If you found this useful, consider giving it a ⭐ — it helps others discover the project.

About

Hyperliquid Telegram Delta Neutral Bot

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages