hyperliquid-trading-bot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hyperliquid Trading Bot

Hyperliquid 交易机器人

Skill by ara.so — Daily 2026 Skills collection.
A configurable grid strategy runner for Hyperliquid DEX. Places layered buy/sell orders around a price range and enforces risk rules (stop loss, take profit, drawdown limits, rebalancing). Primary stack is TypeScript on Node.js 20.19+; a legacy Python tree exists for reference and learning examples.

ara.so 开发的Skill——2026每日技能合集。
一款适用于Hyperliquid DEX的可配置网格策略运行器。可在指定价格区间内挂分层买卖订单,并执行风险规则(止损、止盈、最大回撤限制、再平衡)。核心技术栈为Node.js 20.19+ 上的TypeScript;同时提供了遗留Python版本作为参考和学习示例。

Installation

安装

bash
git clone https://github.com/PolyPulse-Analytics/hyperliquid-trading-bot.git
cd hyperliquid-trading-bot
npm install
bash
git clone https://github.com/PolyPulse-Analytics/hyperliquid-trading-bot.git
cd hyperliquid-trading-bot
npm install

Requirements

环境要求

  • Node.js 20.19+
  • A Hyperliquid wallet private key (use a dedicated testnet key to start)
  • git
Optional for Python examples: uv

  • Node.js 20.19+
  • 一个Hyperliquid钱包私钥(建议使用专用测试网密钥开始)
  • git
Python示例可选依赖:uv

Environment Setup

环境配置

bash
cp .env.example .env
Edit
.env
— minimum required keys:
env
undefined
bash
cp .env.example .env
编辑
.env
文件——至少需要配置以下密钥:
env
undefined

Testnet (recommended to start)

测试网(建议初始使用)

HYPERLIQUID_TESTNET_PRIVATE_KEY=0xYOUR_TESTNET_PRIVATE_KEY_HERE HYPERLIQUID_TESTNET=true
HYPERLIQUID_TESTNET_PRIVATE_KEY=0xYOUR_TESTNET_PRIVATE_KEY_HERE HYPERLIQUID_TESTNET=true

Mainnet (real funds — set carefully)

主网(涉及真实资金——谨慎设置)

HYPERLIQUID_MAINNET_PRIVATE_KEY=0xYOUR_MAINNET_PRIVATE_KEY_HERE

HYPERLIQUID_MAINNET_PRIVATE_KEY=0xYOUR_MAINNET_PRIVATE_KEY_HERE

HYPERLIQUID_TESTNET=false

HYPERLIQUID_TESTNET=false


**Never commit `.env` or share your private key.**

---

**绝对不要提交`.env`文件或分享你的私钥。**

---

Key Commands

核心命令

CommandPurpose
npm start
Run bot using first
active: true
config in
bots/
npm run validate
Validate YAML config structure (no private key needed)
npm test
Run automated tests (grid math, etc.)
npx tsc --noEmit
TypeScript type check
npx tsx ts/src/runBot.ts path/to/config.yaml
Run with explicit config file
命令用途
npm start
使用
bots/
目录中第一个
active: true
的配置运行机器人
npm run validate
验证YAML配置结构(无需私钥)
npm test
运行自动化测试(如网格计算等)
npx tsc --noEmit
TypeScript类型检查
npx tsx ts/src/runBot.ts path/to/config.yaml
指定配置文件运行机器人

Explicit config path (recommended for multi-bot setups)

指定配置文件路径(多机器人场景推荐)

bash
npx tsx ts/src/runBot.ts bots/btc_conservative.yaml
bash
npx tsx ts/src/runBot.ts bots/btc_conservative.yaml

Graceful shutdown

优雅停机

Press Ctrl+C — the engine attempts to cancel all open orders before exiting. Always review logs to confirm cancellation.

按下Ctrl+C——引擎会尝试在退出前取消所有未成交订单。请务必查看日志确认取消状态。

Bot Configuration (YAML)

机器人配置(YAML)

Config files live in
bots/*.yaml
. Only one file should have
active: true
when using auto-discovery via
npm start
.
配置文件存放在
bots/*.yaml
目录下。使用
npm start
自动发现配置时,仅应有一个文件设置
active: true

Full annotated example

完整带注释示例

yaml
name: "btc_grid_testnet"
active: true

exchange:
  type: "hyperliquid"
  testnet: true          # Set false for mainnet — also set HYPERLIQUID_TESTNET=false in .env

account:
  max_allocation_pct: 10.0   # Max % of account balance to allocate to this grid

grid:
  symbol: "BTC"              # Hyperliquid market symbol
  levels: 10                 # Number of buy/sell levels on each side
  price_range:
    mode: "auto"             # "auto" or "manual"
    auto:
      range_pct: 5.0         # Spread ±5% from current price
    # manual:
    #   lower: 90000
    #   upper: 100000

risk_management:
  stop_loss_enabled: false
  stop_loss_pct: 8.0         # Trigger if price drops X% from entry

  take_profit_enabled: false
  take_profit_pct: 15.0      # Trigger if price rises X% from entry

  max_drawdown_pct: 15.0     # Max allowed drawdown before halting
  max_position_size_pct: 40.0 # Max position as % of allocated capital

  rebalance:
    price_move_threshold_pct: 12.0  # Rebalance grid if price moves outside this %

monitoring:
  log_level: "INFO"          # DEBUG, INFO, WARN, ERROR
yaml
name: "btc_grid_testnet"
active: true

exchange:
  type: "hyperliquid"
  testnet: true          # 主网请设为false——同时需在.env中设置HYPERLIQUID_TESTNET=false

account:
  max_allocation_pct: 10.0   # 分配给该网格的账户余额最大百分比

grid:
  symbol: "BTC"              # Hyperliquid市场交易对符号
  levels: 10                 # 买卖两侧的分层订单数量
  price_range:
    mode: "auto"             # 可选"auto"或"manual"
    auto:
      range_pct: 5.0         # 基于当前价格上下浮动±5%
    # manual:
    #   lower: 90000
    #   upper: 100000

risk_management:
  stop_loss_enabled: false
  stop_loss_pct: 8.0         # 价格较入场价下跌X%时触发止损

  take_profit_enabled: false
  take_profit_pct: 15.0      # 价格较入场价上涨X%时触发止盈

  max_drawdown_pct: 15.0     # 允许的最大回撤比例,超过则暂停机器人
  max_position_size_pct: 40.0 # 持仓占分配资金的最大比例

  rebalance:
    price_move_threshold_pct: 12.0  # 价格波动超过该比例时重新平衡网格

monitoring:
  log_level: "INFO"          # 可选DEBUG、INFO、WARN、ERROR

Manual price range example

手动价格区间示例

yaml
grid:
  symbol: "ETH"
  levels: 8
  price_range:
    mode: "manual"
    manual:
      lower: 3000
      upper: 3600

yaml
grid:
  symbol: "ETH"
  levels: 8
  price_range:
    mode: "manual"
    manual:
      lower: 3000
      upper: 3600

Common Patterns

常见使用场景

Running multiple bots with different configs

运行多个不同配置的机器人

Do not use
active: true
— call each explicitly:
bash
undefined
不要设置
active: true
——直接指定每个配置文件运行:
bash
undefined

Terminal 1

终端1

npx tsx ts/src/runBot.ts bots/btc_conservative.yaml
npx tsx ts/src/runBot.ts bots/btc_conservative.yaml

Terminal 2

终端2

npx tsx ts/src/runBot.ts bots/eth_aggressive.yaml
undefined
npx tsx ts/src/runBot.ts bots/eth_aggressive.yaml
undefined

Validate before running (CI/pre-flight)

运行前验证(CI/预检查)

bash
npm run validate && npm start
bash
npm run validate && npm start

Testnet workflow before going live

上线前的测试网流程

  1. Set
    HYPERLIQUID_TESTNET=true
    in
    .env
  2. Set
    exchange.testnet: true
    in your YAML
  3. Fund via Hyperliquid testnet faucet
  4. Run
    npm run validate
    then
    npm start
  5. Watch logs — verify orders appear in testnet UI
  6. Only then flip both flags to
    false
    for mainnet

  1. .env
    中设置
    HYPERLIQUID_TESTNET=true
  2. 在YAML配置中设置
    exchange.testnet: true
  3. 通过Hyperliquid测试网水龙头获取测试资金
  4. 运行
    npm run validate
    后执行
    npm start
  5. 查看日志——验证订单是否在测试网界面显示
  6. 确认无误后再将两个参数都改为
    false
    切换到主网

Python Learning Examples

Python学习示例

bash
undefined
bash
undefined

Install Python deps

安装Python依赖

uv sync
uv sync

Validate Python bot config

验证Python机器人配置

uv run src/run_bot.py --validate
uv run src/run_bot.py --validate

Run Python bot (legacy)

运行Python版机器人(遗留版本)

uv run src/run_bot.py
uv run src/run_bot.py

Educational scripts

教学脚本

uv run learning_examples/01_websockets/realtime_prices.py uv run learning_examples/02_market_data/get_all_prices.py uv run learning_examples/04_trading/place_limit_order.py
undefined
uv run learning_examples/01_websockets/realtime_prices.py uv run learning_examples/02_market_data/get_all_prices.py uv run learning_examples/04_trading/place_limit_order.py
undefined

Python: Fetch real-time prices via WebSocket

Python:通过WebSocket获取实时价格

python
undefined
python
undefined

learning_examples/01_websockets/realtime_prices.py pattern

learning_examples/01_websockets/realtime_prices.py 示例代码

import asyncio from hyperliquid.websocket_manager import WebsocketManager
async def on_message(msg): print(msg)
async def main(): ws = WebsocketManager(base_url="https://api.hyperliquid-testnet.xyz") await ws.subscribe({"type": "allMids"}, on_message) await asyncio.sleep(30)
asyncio.run(main())
undefined
import asyncio from hyperliquid.websocket_manager import WebsocketManager
async def on_message(msg): print(msg)
async def main(): ws = WebsocketManager(base_url="https://api.hyperliquid-testnet.xyz") await ws.subscribe({"type": "allMids"}, on_message) await asyncio.sleep(30)
asyncio.run(main())
undefined

Python: Place a limit order (testnet)

Python:挂限价单(测试网)

python
undefined
python
undefined

learning_examples/04_trading/place_limit_order.py pattern

learning_examples/04_trading/place_limit_order.py 示例代码

import os from hyperliquid.exchange import Exchange from hyperliquid.utils import constants import eth_account
private_key = os.environ["HYPERLIQUID_TESTNET_PRIVATE_KEY"] account = eth_account.Account.from_key(private_key)
exchange = Exchange(account, constants.TESTNET_API_URL)
import os from hyperliquid.exchange import Exchange from hyperliquid.utils import constants import eth_account
private_key = os.environ["HYPERLIQUID_TESTNET_PRIVATE_KEY"] account = eth_account.Account.from_key(private_key)
exchange = Exchange(account, constants.TESTNET_API_URL)

Place a limit buy for 0.001 BTC at $90,000

以90,000美元的价格挂0.001 BTC的限价买单

result = exchange.order( "BTC", is_buy=True, sz=0.001, limit_px=90000, order_type={"limit": {"tif": "Gtc"}}, ) print(result)

---
result = exchange.order( "BTC", is_buy=True, sz=0.001, limit_px=90000, order_type={"limit": {"tif": "Gtc"}}, ) print(result)

---

Troubleshooting

故障排查

Bot exits immediately without placing orders

机器人启动后立即退出,未下单

  • Run
    npm run validate
    first — check for YAML syntax errors
  • Confirm
    active: true
    is set (or pass config path explicitly)
  • Verify
    HYPERLIQUID_TESTNET
    in
    .env
    matches
    exchange.testnet
    in YAML
  • 先运行
    npm run validate
    ——检查YAML语法错误
  • 确认配置文件中设置了
    active: true
    (或明确传入配置文件路径)
  • 验证
    .env
    中的
    HYPERLIQUID_TESTNET
    与YAML中的
    exchange.testnet
    参数一致

Orders placed but immediately cancelled

订单已挂单但立即被取消

  • Testnet account may have insufficient balance — refund via faucet
  • max_allocation_pct
    may be too low for minimum order sizes on the symbol
  • 测试网账户余额不足——通过水龙头补充资金
  • max_allocation_pct
    设置过低,无法满足该交易对的最小下单量要求

TypeScript compilation errors

TypeScript编译错误

bash
npx tsc --noEmit
Check Node.js version — must be 20.19+:
bash
node --version
bash
npx tsc --noEmit
检查Node.js版本——必须为20.19+
bash
node --version

Python
uv
not found

Python
uv
未找到

bash
pip install uv
bash
pip install uv

or

undefined
undefined

Private key errors / authentication failures

私钥错误/认证失败

  • Confirm the key in
    .env
    matches the funded testnet wallet
  • Key must include
    0x
    prefix
  • Never use a mainnet key on testnet configs — keep separate keys
  • 确认
    .env
    中的密钥与已充值的测试网钱包一致
  • 密钥必须包含
    0x
    前缀
  • 绝对不要在测试网配置中使用主网密钥——请分开使用不同密钥

Grid not rebalancing when price moves

价格波动时网格未重新平衡

Check
risk_management.rebalance.price_move_threshold_pct
— default is
12.0
. Lower it if you want more frequent rebalancing (increases gas/fees).

检查
risk_management.rebalance.price_move_threshold_pct
——默认值为
12.0
。若需要更频繁的再平衡可降低该值(会增加Gas/手续费)。

Project Structure

项目结构

hyperliquid-trading-bot/
├── bots/                    # YAML strategy configs
│   └── btc_conservative.yaml
├── ts/src/
│   └── runBot.ts            # Main TypeScript entrypoint
├── src/
│   └── run_bot.py           # Legacy Python entrypoint
├── learning_examples/       # Educational Python scripts
│   ├── 01_websockets/
│   ├── 02_market_data/
│   └── 04_trading/
├── .env.example             # Environment variable template
├── package.json
└── pyproject.toml

hyperliquid-trading-bot/
├── bots/                    # YAML策略配置文件
│   └── btc_conservative.yaml
├── ts/src/
│   └── runBot.ts            # TypeScript主入口文件
├── src/
│   └── run_bot.py           # Python遗留版本入口文件
├── learning_examples/       # Python教学脚本
│   ├── 01_websockets/
│   ├── 02_market_data/
│   └── 04_trading/
├── .env.example             # 环境变量模板
├── package.json
└── pyproject.toml

Risk Reminder

风险提示

  • Always start on testnet with a dedicated key
  • Use
    max_allocation_pct
    to limit exposure
  • Enable
    max_drawdown_pct
    as a safety net before enabling stop loss/take profit
  • Review open orders in the Hyperliquid UI after every bot restart
  • This software is provided "as is" — you are responsible for your capital
  • 始终使用专用密钥从测试网开始
  • 使用
    max_allocation_pct
    限制资金暴露
  • 在启用止损/止盈前,先开启
    max_drawdown_pct
    作为安全保障
  • 每次机器人重启后,在Hyperliquid界面检查未成交订单
  • 本软件按“原样”提供——你需自行对资金负责