Skip to content

nahime0/hyperliquid-bot

Repository files navigation

Hyperliquid Perpetual Trading Bot

Python Hyperliquid Claude AI License Status

Have you always dreamed of losing money through crypto? Well, this project is just right for you. I started this project to experiment whether it was possible to build a bot that, with the help of artificial intelligence, could generate revenue through cryptocurrencies. The answer is simple: no, it's not possible. Or at least this bot can't do it. Or maybe I just can't. Who knows.

This bot uses an absurd number of well-known strategies to generate "signals" for potential trades. These signals are then sent to the AI (via Claude Code CLI or Cursor Agent CLI), which has the final say on entry decisions. There are also a bunch of techniques to maximize profit (Trailing Stop) and minimize losses (Stop Loss, etc.). However, after a week of use the balance is at a slight loss.

The project was built with heavy use of Claude Code. All the more reason I'd advise against using it. But if you want to take a look at what crypto trading strategies look like, or you're just curious, feel free to browse the code.

The project is not finished. Some things only half-work (for example, parameters have been set in the DB but aren't yet read by the bot, which still uses the .env file). There's a minimal web interface (in the web/ folder) where you can monitor active trades, coins, generated events, and AI decisions.

You can start it with:

cd web && npm run dev

Have fun!


Automated Python trading bot for Hyperliquid Perpetual Futures, with an optional AI advisor (Claude Code CLI). The bot runs 24/7 with Mean Reversion + RSI Divergence strategies (LONG and SHORT), conservative leverage (2-3x), and ultra-low fees (0.06% round-trip).

Why Hyperliquid: Binance Spot fees are too high (0.15% RT) for micro-profits. Binance Futures is blocked for EU users (MiCA). Hyperliquid offers 3x lower fees, shorting capability, leverage, and no KYC.

USDC: Hyperliquid settles natively in USDC. USDT is unavailable for EU users on Binance due to MiCA regulation.


Table of Contents

  1. Overview
  2. Architecture
  3. AI Advisor
  4. Strategies
  5. Risk Management
  6. Setup
  7. Running
  8. Dashboard
  9. Database
  10. Project Structure
  11. Configuration
  12. Detailed Documentation

Overview

The bot runs a continuous loop that every 60 seconds:

  1. Collects market data via Hyperliquid WebSocket and REST APIs
  2. Calculates technical indicators (RSI, Bollinger Bands, MACD, EMA) on multiple timeframes (15m, 1h)
  3. Filters trends with EMA50/EMA200 on 1h (BULLISH/BEARISH/NEUTRAL)
  4. Generates autonomous decisions (BUY, SHORT, CLOSE) through coded rules (Mean Reversion)
  5. Optional AI advisor (Claude Code CLI) approves/defers/adjusts
  6. Validates with Risk Manager (kill switch, drawdown, Kelly sizing)
  7. Executes the order on Hyperliquid (or logs it in paper mode)

Key Features

  • Rule-based + AI advisor: decisions are generated by coded rules, the AI (Claude Code CLI) acts as an optional advisor
  • LONG and SHORT: full support for both directions on perpetual futures
  • Simple AI advisor: a single CLI call per cycle, with defer and adjustment support
  • Rigorous risk management: kill switch, daily pause, Kelly Criterion for sizing, trailing stop, time stop
  • Conservative leverage: 2-3x with cross margin
  • Ultra-low fees: 0.06% round-trip (vs 0.15% on Binance Spot)
  • Web dashboard: real-time monitoring via Next.js (in web/)
  • Telegram notifications: alerts on executed trades and critical conditions
  • Automatic discovery: discovers up to 60 perpetual coins by volume

Monitored Coins

Type Coins
Core (always included) BTC, ETH, SOL
Discovery (top by volume) Up to 60 perpetual coins

Architecture

                        +---------------------------------------------+
                        |              MAIN LOOP (60s)                |
                        |                                             |
                        |  1. Risk Refresh -------------+             |
                        |  2. Check Positions -----------+             |
                        |  3. Update Trend Filter -------+             |
                        |  4. Update Strategies ---------+             |
                        |  5. Generate Candidates --------+             |
                        |  5b. Check Deferred ------------+             |
                        |  6. AI Advisor (optional) ------+             |
                        |  7. Risk Validate --------------+             |
                        |  8. Execute --------------------+             |
                        +----------------+----------------------------+
                                         |
              +--------------------------+---------------------------+
              |                          |                          |
    +---------v---------+    +----------v----------+    +---------v---------+
    | HYPERLIQUID CLIENT |    |    AI ADVISOR        |    |   RISK MANAGER    |
    |                    |    |                      |    |                   |
    |  REST (via SDK)    |    |  Claude Code CLI     |    |  Kill Switch      |
    |  WebSocket feeds   |    |  1 call/cycle        |    |  Daily Pause      |
    |  Market orders     |    |  Structured JSON     |    |  Liquidation Mon. |
    |  Position mgmt     |    |  Deferred tracking   |    |  Kelly Criterion  |
    |  Leverage control  |    |  SL/TP adjustments   |    |  Trailing Stop    |
    +---------+---------+    +----------------------+    +---------+---------+
              |                                                     |
    +---------v---------+    +---------------------+    +---------v---------+
    |   MARKET DATA      |    |   STRATEGIES         |    |  POSITION TRACKER |
    |                    |    |                      |    |                   |
    |  allMids WS stream |    |  Mean Reversion      |    |  LONG / SHORT     |
    |  Candle WS streams |    |  RSI Divergence      |    |  Trailing SL      |
    |  Candle cache      |    |  Multi-Strategy      |    |  Time Stop        |
    |  RSI, BB, EMA      |    |  Trend Filter        |    |  Direction-aware   |
    |  indicators        |    |  Cooldown            |    |  AI adjustments   |
    +-------------------+    +---------------------+    +-------------------+
              |
    +---------v---------+    +-------------------+
    |    DATABASE        |    |   DASHBOARD       |
    |                    |    |                   |
    |  SQLite (aiosqlite)|    |  Next.js (web/)   |
    |  Trades, Positions |    |  SQLite readonly  |
    |  Balance Snapshots |    |  bot_status.json  |
    +-------------------+    +-------------------+

Tech Stack

Component Technology
Language Python 3.11+ (async/await)
Exchange hyperliquid-python-sdk (REST + WebSocket)
AI Advisor Claude Code CLI (structured JSON)
Indicators ta library (RSI, BB, MACD, EMA)
Data pandas for time series, aiosqlite for persistence
Dashboard Next.js (in web/, standalone)
Notifications Telegram Bot API via aiohttp
Auth eth-account (EIP-712 wallet signing)
Config python-dotenv + frozen dataclasses

AI Advisor

The bot uses an optional AI advisor based on Claude Code CLI. Strategies generate candidate decisions, the AI reviews them and can:

  • Approve entries (BUY/SHORT) with optional SL/TP/size adjustments
  • Defer entries (HOLD with conditions: wait cycles or target price)
  • Close open positions (CLOSE)
  • Adjust positions (ADJUST: SL/TP/leverage)
Strategies -> Candidates -> AI Advisor (1 call/cycle) -> Risk Manager -> Execute

A single CLI call per cycle, with structured JSON (--json-schema). If there are no positions or opportunities, the call is skipped. On error/timeout: log warning, the bot continues autonomously.

For details, see docs/ai-engine.md.


Strategies

Mean Reversion (LONG + SHORT)

The main strategy generates autonomous decisions based on coded rules. The AI only intervenes as an optional reviewer.

LONG Entry Conditions (all must be true)

Condition Threshold
Trend (1h) BULLISH (EMA50 > EMA200, price > EMA50, slope > 0)
RSI (15m) < 25 (deep oversold)
Bollinger Band (15m) Price <= lower BB * 1.005
Volume Ratio >= 1.2 (above average)
Macro RSI (1h) < 60 (no divergence)
Funding rate
Cooldown No recent trade on the same coin
Position No open position on the same coin

SHORT Entry Conditions (all must be true)

Condition Threshold
Trend (1h) BEARISH (EMA50 < EMA200, price < EMA50, slope < 0)
RSI (15m) > 75 (strict overbought)
Bollinger Band (15m) Price >= upper BB * 0.995
Volume Ratio >= 1.2
Macro RSI (1h) > 40
Funding rate
Cooldown No recent trade
Position No open position

Exit Conditions

Direction Trigger Action
LONG RSI > 70 OR price >= upper BB CLOSE
SHORT RSI < 30 OR price <= lower BB CLOSE
Both SL/TP reached Auto-close
Both Trailing SL reached Auto-close
Both Time stop (4h+ with PnL < 0.5%) Auto-close

Trend Filter

Classifies each coin as BULLISH, BEARISH, or NEUTRAL based on EMA50/EMA200 on 1h candles.

BULLISH:  EMA50 > EMA200  AND  price > EMA50  AND  slope > 0
BEARISH:  EMA50 < EMA200  AND  price < EMA50  AND  slope < 0
NEUTRAL:  everything else

Risk Management

The Risk Manager has absolute veto power over every decision. Even if the strategy says BUY, the Risk Manager can block it.

Rules

Rule Value Description
Max per trade 10% of bankroll No trade risks more than 10% of margin
Stop loss -1% per trade Applied automatically if not specified
Take profit +1.5% per trade Suggested automatically if not specified
Max daily drawdown -5% Automatic pause until midnight UTC
Max total drawdown -15% from peak Kill switch: stops EVERYTHING
Max open positions 5 Blocks new entries when reached
Minimum balance 50 USDC Kill switch if it drops below
Consecutive losses 5 Kill switch
Minimum confidence 0.5 Blocks trades with too low confidence
Max leverage 3x Leverage limit
Liquidation buffer 5% Warning if position close to liquidation
Minimum holding 15 min Prevents too-quick closures

Trailing Stop

Phase Trigger Action
Break-even Gain >= 1.0% SL moves to entry price
Trailing Gain >= 1.5% SL follows at 1.0% distance
Tight trailing Gain >= 2.5% SL tightens to 0.75% distance

Direction-aware: for LONG the SL rises, for SHORT the SL falls.

Time Stop

Positions open for more than 4 hours with PnL < 0.5% are automatically closed.

Position Sizing: Fractional Kelly

f = (win_rate * payoff_ratio - (1 - win_rate)) / payoff_ratio
size = bankroll * (f / 4)  # conservative quarter-Kelly

With adjustments:

  • Cold start (< 10 trades): fixed 5% of bankroll
  • Confidence scaling: size multiplied by confidence
  • Hard cap: never more than the configured max_trade_pct
  • Minimum: orders below 10 USDC are discarded

Cooldown

Type Duration Trigger
Per-symbol 30 min After a loss on the same coin
Global 15 min After 3 consecutive losses

Setup

Prerequisites

  • Python 3.11+ (tested with 3.14)
  • Hyperliquid wallet (or dedicated API wallet)
  • Claude Code CLI installed (for AI advisor, optional)
  • (Optional) Telegram bot for notifications

Installation

git clone <repo-url>
cd binance

python3 -m venv .venv
source .venv/bin/activate

pip install -r requirements.txt

Dependencies

hyperliquid-python-sdk    # Hyperliquid SDK (REST + WebSocket)
eth-account               # Wallet signing (EIP-712)
pandas>=2.1.0             # Time series
ta>=0.11.0                # Technical indicators (RSI, BB, MACD, EMA)
aiosqlite>=0.19.0         # Async SQLite
python-dotenv>=1.0.0      # Config from .env
aiohttp>=3.9.0            # Telegram notifications

.env Configuration

Copy .env.example and edit:

# Hyperliquid API
HL_PRIVATE_KEY=0x...          # wallet private key
HL_ACCOUNT_ADDRESS=0x...      # public address
HL_TESTNET=true               # true=testnet, false=mainnet
HL_DEFAULT_LEVERAGE=2          # leverage (2-3x recommended)
HL_MARGIN_MODE=cross           # cross or isolated
HL_MAX_FUNDING_RATE=0.0005     # max acceptable funding rate

# AI Advisor (optional, requires Claude Code CLI)
AI_MODEL=opus              # model (opus, sonnet, haiku)
AI_TIMEOUT=180             # timeout in seconds

# Telegram (optional)
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=

See the Configuration section for all available variables.


Running

Modes

Flag Description
--testnet Use Hyperliquid testnet (default)
--live Use mainnet (caution: real money!)
--paper Paper trading: logs decisions but doesn't place orders
--no-ai Disables AI review, uses pure coded rules
--once Runs a single cycle then exits

Examples

# Testnet with AI review (recommended starting mode)
.venv/bin/python main.py

# Paper trading (no real orders, logs everything)
.venv/bin/python main.py --paper

# Single cycle to verify everything works
.venv/bin/python main.py --paper --once

# Without AI review (pure rule-based)
.venv/bin/python main.py --no-ai

# Quick test (paper + no AI + single cycle)
.venv/bin/python main.py --paper --no-ai --once

# MAINNET TRADING (use with caution!)
.venv/bin/python main.py --live

Graceful Shutdown

The bot handles SIGINT (Ctrl+C) and SIGTERM:

  1. Saves a final balance snapshot
  2. Closes WebSocket connections
  3. Closes the database
  4. Closes the Hyperliquid client

Dashboard

Standalone web dashboard based on Next.js, in the web/ folder. Reads the SQLite database in readonly mode and bot_status.json to display bot state. The dashboard is separate from the bot process.

# Development (with hot reload)
cd web && npm run dev

# Production
cd web && npm run build && npm start

Open http://localhost:3000 in the browser.

Section Content
Balance Current balance, peak, drawdown
Equity Curve Historical balance chart
AI Decisions Latest decisions with action, confidence, reasoning
Trades Last 50 trades with P&L
Trade Stats Win rate, profit factor, consecutive losses
Positions Open positions with direction, leverage, liquidation price
Bot Status Mode, current cycle, strategy state

Database

SQLite (via aiosqlite) with 5 main tables. Full schema in docs/database.md.

Table Content
trades Trade history with PnL, direction
positions Open/closed positions with SL/TP, trailing, direction, leverage
balance_snapshots Balance history for equity curve
orders Placed orders

The database is located at data/trading_bot.db.


Project Structure

binance/
├── main.py                          # Entry point: orchestrator (Bot class)
├── CLAUDE.md                        # Instructions for Claude Code
├── README.md                        # This documentation
├── requirements.txt                 # Python dependencies
├── .env                             # Environment variables (DO NOT commit!)
├── .env.example                     # .env template
│
├── docs/                            # Detailed documentation
│   ├── architecture.md              # System architecture
│   ├── strategies.md                # Trading strategies
│   ├── risk-management.md           # Risk management system
│   ├── ai-engine.md                 # AI Decision Engine
│   ├── configuration.md             # All configuration variables
│   ├── database.md                  # Database schema
│   └── deployment.md                # Setup, installation, deployment
│
├── config/
│   ├── __init__.py
│   ├── settings.py                  # Dataclass: HyperliquidConfig, AIConfig, RiskConfig, etc.
│   └── pairs.py                     # CORE_COINS, ALL_COINS, discover_perp_coins()
│
├── core/
│   ├── __init__.py
│   ├── client.py                    # HyperliquidClient: async wrapper with retry/backoff
│   ├── market_data.py               # MarketData: WebSocket feeds, candle cache, indicators
│   ├── ai_advisor.py                # AI Advisor: Claude Code CLI integration
│   └── types.py                     # Decision dataclass
│
├── strategies/
│   ├── __init__.py                  # Exports Strategy, MeanReversionStrategy, TrendFilter
│   ├── base.py                      # ABC Strategy: start(), stop(), update(), get_state()
│   ├── mean_reversion.py            # Mean Reversion: LONG + SHORT, autonomous signals
│   ├── rsi_divergence.py            # RSI Divergence: swing detection
│   ├── multi_strategy.py            # Multi-strategy aggregator
│   ├── trend_filter.py              # EMA50/EMA200 trend classification
│   ├── cooldown.py                  # CooldownTracker: per-symbol + global
│   └── grid.py                      # GridStrategy (disabled, kept for history)
│
├── risk/
│   ├── __init__.py
│   ├── position_sizer.py            # Kelly Criterion f/4, confidence scaling
│   ├── position_tracker.py          # Position tracking: LONG/SHORT, trailing SL, time stop
│   └── risk_manager.py              # Kill switch, daily pause, validation, metrics
│
├── data/
│   ├── __init__.py
│   ├── db.py                        # Database: async SQLite, schema, CRUD, migrations
│   ├── backtest.py                  # BacktestEngine: simulation on historical data
│   ├── history/                     # Downloaded CSVs (e.g. ETH_15m.csv)
│   ├── backtest_results/            # Backtest output (equity curve CSV + PNG)
│   ├── trading_bot.db               # SQLite database (generated at runtime)
│   └── bot_status.json              # Live status for dashboard (written by bot)
│
├── schemas/
│   ├── __init__.py
│   └── ai_advisor_output.json       # JSON Schema for AI advisor output
│
├── prompts/
│   ├── __init__.py
│   └── ai_advisor.md                # System prompt for AI advisor
│
├── web/                                 # Next.js dashboard (standalone)
│   ├── package.json
│   ├── next.config.ts
│   └── src/                             # Next.js sources (App Router)
│
├── utils/
│   ├── __init__.py
│   ├── logger.py                    # Structured logging: console + rotating file (5MB x 5)
│   └── telegram.py                  # TelegramNotifier: notify_trade(), notify_alert()
│
├── scripts/
│   ├── __init__.py
│   ├── test_connection.py           # Hyperliquid connection test
│   ├── download_history.py          # Download historical klines
│   ├── backtest_runner.py           # Run backtest with parameter sweep
│   └── strategy_sweep.py            # Strategy parameter sweep
│
├── tests/
│   └── __init__.py
│
└── logs/
    └── bot.log                      # Log file (5MB rotation x 5)

Configuration

Hyperliquid API

Variable Default Description
HL_PRIVATE_KEY (empty) Wallet private key (EIP-712)
HL_ACCOUNT_ADDRESS (empty) Wallet public address
HL_TESTNET true true for testnet, false for mainnet
HL_DEFAULT_LEVERAGE 2 Default leverage (2-3x recommended)
HL_MARGIN_MODE cross cross or isolated
HL_MAX_FUNDING_RATE 0.0005 Max acceptable funding rate (0.05%/8h)

AI Advisor

Variable Default Description
AI_DECISION_INTERVAL 60 Seconds between cycles
AI_MODEL opus Claude Code model (opus, sonnet, haiku)
AI_TIMEOUT 180 CLI call timeout (seconds)
AI_MIN_CONFIDENCE 0.6 Below this threshold -> forced HOLD
AI_FALLBACK_ON_ERROR HOLD Default action if the AI doesn't respond
AI_LOG_REASONING true Log AI reasoning
AI_ADVISOR claude AI backend (claude or cursor)

Risk Management

Variable Default Description
MAX_TRADE_PCT 10 Max % of bankroll per trade
STOP_LOSS_PCT 1.0 Automatic stop loss (%)
TAKE_PROFIT_PCT 1.5 Automatic take profit (%)
MAX_DAILY_DRAWDOWN_PCT 5.0 Max daily drawdown -> pause
MAX_TOTAL_DRAWDOWN_PCT 15.0 Max total drawdown -> kill switch
MAX_OPEN_POSITIONS 5 Max open positions
MIN_BALANCE_USDC 50.0 Minimum balance -> kill switch
TRAILING_BREAKEVEN_PCT 1.0 Move SL to entry after +X%
TRAILING_START_PCT 1.5 Start trailing after +X%
TRAILING_DISTANCE_PCT 1.0 Trail distance from max/min
TRAILING_TIGHT_PCT 2.5 Tighten trail after +X%
TRAILING_TIGHT_DISTANCE_PCT 0.75 Tight trail distance
TIME_STOP_HOURS 4.0 Close positions after X hours
TIME_STOP_MIN_PNL_PCT 0.5 Only if PnL < X%
SYMBOL_COOLDOWN_SEC 1800 Per-symbol cooldown (30 min)
GLOBAL_COOLDOWN_SEC 900 Global cooldown (15 min)
GLOBAL_COOLDOWN_LOSSES 3 Trigger cooldown after N losses

Market Discovery

Variable Default Description
MIN_PAIR_VOLUME 50000 Minimum 24h volume (USDC)
MAX_COINS 60 Max perpetual coins to monitor

Other

Variable Default Description
LOG_LEVEL INFO Log level
DB_PATH data/trading_bot.db SQLite database path
TELEGRAM_BOT_TOKEN (empty) Telegram bot token
TELEGRAM_CHAT_ID (empty) Telegram chat ID

Detailed Documentation

For in-depth information, see the docs/ folder:

Document Content
architecture.md System architecture, data flow, components
strategies.md Mean Reversion LONG/SHORT, Trend Filter, signals
risk-management.md Kill switch, trailing stop, Kelly sizing, cooldown
ai-engine.md AI Advisor (Claude Code CLI), schema, defer
DEVELOPMENT.md Technical guide, project structure, conventions
configuration.md All .env variables with details
database.md Complete table schema, migrations
deployment.md Setup, installation, server deployment

Important Notes

  • Never run the bot in --live mode without validating on testnet first
  • The .env file contains private keys: do not commit it
  • Hyperliquid fees are 0.045% taker per leg (0.06% round-trip)
  • With 2x leverage and 1% SL, liquidation risk is practically zero
  • The bot logs everything to logs/bot.log (5MB rotation, 5 backup files)
  • For server deployment, use systemd or supervisor for automatic restarts

Releases

No releases published

Packages

 
 
 

Contributors