DEV Community

guardlabs_team
guardlabs_team

Posted on • Originally published at nexus-bot.pro

I Built a Hyperliquid Copy Trading Bot in 15 Minutes — Here's the Stack

I Built a Hyperliquid Copy Trading Bot in 15 Minutes — Here's the Stack

The crypto trading world is buzzing about Hyperliquid, and for good reason. It's fast, it's decentralized, and its volume is exploding. If you're a developer with a trading itch, this is the new playground. Forget the slow, clunky interfaces of the past; we're in the era of sub-second execution on-chain.

I've been building trading bots for years, and the moment I saw Hyperliquid's architecture, I knew I had to get my hands dirty. My goal was simple: build the core of a copy trading bot—one that listens to a "leader" wallet and mimics its trades—as quickly as possible.

It took me about 15 minutes to get the essential components working. Here’s the tactical, no-fluff breakdown of the stack and the "gotchas" you need to know.

1. Why Hyperliquid is a Game-Changer

If you're coming from Binance, Bybit, or any other centralized exchange (CEX), Hyperliquid feels different. It's a decentralized perpetuals exchange (DEX) built on its own L1 blockchain. This isn't just a philosophical difference; it has practical implications for bot builders:

  • Self-Custody: You trade directly from your wallet. No more depositing funds onto an exchange and praying they don't get hacked or go insolvent. Your keys, your crypto.
  • Blazing Speed: Because it's a purpose-built L1, it doesn't suffer from the congestion of general-purpose chains like Ethereum. It's designed for one thing: a high-performance order book. This means low latency and minimal slippage.
  • Transparency: Every trade, liquidation, and state change is on-chain. You can verify everything. For a copy trader, this means you can track a leader wallet with 100% accuracy.
  • Explosive Growth: The platform's Total Value Locked (TVL) and trading volume are skyrocketing. More volume means more opportunities and better liquidity.

For a bot developer, this is the holy trinity: speed, transparency, and control.

2. The WebSocket: Your Bot's Nervous System

The heart of any real-time trading bot is its connection to the data firehose. For our copy trader, we don't need to listen to the public order book. We need to listen to the private actions of a specific user. Hyperliquid's WebSocket API makes this incredibly straightforward.

You can subscribe to the userEvents stream for any public wallet address. This stream will push real-time updates whenever that user's orders are filled, triggered, or modified. This is the "copy" mechanism.

Here’s a Python snippet that connects to the WebSocket and listens for fills from a specific user address.

import asyncio
import json
import websockets

# The address of the "leader" trader you want to copy
LEADER_ADDRESS = "0x_YOUR_LEADER_WALLET_ADDRESS" 

async def listen_to_hyperliquid():
    """
    Connects to the Hyperliquid WebSocket and listens for user fill events.
    """
    uri = "wss://api.hyperliquid.xyz/ws"
    async with websockets.connect(uri) as websocket:
        # Subscription message for a specific user's events
        subscription_message = {
            "method": "subscribe",
            "subscription": {
                "type": "userEvents",
                "user": LEADER_ADDRESS
            }
        }
        await websocket.send(json.dumps(subscription_message))
        print(f"Subscribed to user events for {LEADER_ADDRESS}")

        while True:
            try:
                message = await websocket.recv()
                data = json.loads(message)

                # We only care about the 'fills' data in the userEvents stream
                if data.get("channel") == "userEvents" and "fills" in data.get("data", {}):
                    fills = data["data"]["fills"]
                    if fills:
                        for fill in fills:
                            # This is where you would trigger your own trade logic
                            print("--- LEADER TRADE DETECTED ---")
                            print(f"  Coin: {fill['coin']}")
                            print(f"  Side: {'BUY' if fill['side'] == 'B' else 'SELL'}")
                            print(f"  Size: {fill['sz']}")
                            print(f"  Price: {fill['px']}")
                            print("--------------------------")
                            # --- YOUR ORDER PLACEMENT LOGIC GOES HERE ---

            except websockets.ConnectionClosed:
                print("WebSocket connection closed. Reconnecting...")
                # Implement reconnection logic here
                await asyncio.sleep(5)
                break # Or loop to reconnect

if __name__ == "__main__":
    asyncio.run(listen_to_hyperliquid())
Enter fullscreen mode Exit fullscreen mode

This snippet is the core of our listening module. When a fill is detected, you simply parse the details and trigger your own order.

3. Order Placement Gotchas

Listening is easy. Executing correctly is where the money is made or lost. The Hyperliquid Python SDK is excellent, but you need to be aware of a few critical details that can trip you up.

  • Margin Model: Hyperliquid uses cross-margin by default across all positions. This means a losing position can drain your entire account balance. If you're used to isolated margin on Binance, this is a massive "gotcha." You must manage your risk at the account level.
  • Leverage is Per-Asset: You don't set leverage on a per-trade basis. You set your desired leverage for a specific asset (e.g., 10x on ETH) once. All subsequent trades for that asset will use that leverage setting until you change it.
  • It's USDC, not USDT: The collateral currency on Hyperliquid is USDC. Don't send USDT to your trading address.
  • cloid is Your Friend: When placing an order, you can provide a cloid (Client Order ID). This is a unique identifier you generate. If your bot disconnects and tries to place the same order again, Hyperliquid will reject the duplicate cloid, preventing you from accidentally doubling your position. Always use it.

Here’s a simplified order placement function using the SDK.

from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants

def place_copy_trade(info: Info, exchange: Exchange, fill_data: dict, your_wallet):
    """
    Places a market order based on a detected leader fill.
    NOTE: This is a simplified example. Production code needs robust error handling.
    """
    coin = fill_data["coin"]
    is_buy = fill_data["side"] == "B"
    size_in_usd = float(fill_data["px"]) * float(fill_data["sz"]) # Simplified size logic

    # Example: We decide to trade 1/10th of the leader's size
    our_trade_size = round(float(fill_data["sz"]) / 10, 3) 

    # Get the minimum order size for the asset
    meta = info.meta()
    asset_info = next(asset for asset in meta["universe"] if asset["name"] == coin)
    min_order_size = float(asset_info["minOrderSz"])

    if our_trade_size < min_order_size:
        print(f"Trade size {our_trade_size} is below minimum {min_order_size}. Skipping.")
        return

    # The actual order placement call
    order_result = exchange.order(
        coin, 
        is_buy, 
        our_trade_size, 
        None, # Limit price is None for a market order
        {"limit": {"tif": "Gtc"}} # Good-Til-Canceled
    )

    if order_result["status"] == "ok":
        print(f"Successfully placed {'BUY' if is_buy else 'SELL'} order for {our_trade_size} {coin}.")
    else:
        print(f"Error placing order: {order_result['error']}")

# You would initialize the info, exchange, and wallet objects
# and call this function inside your WebSocket listener.
Enter fullscreen mode Exit fullscreen mode

4. Latency is King: Hetzner in Finland

In copy trading, every millisecond counts. The faster you can react to the leader's trade, the closer your entry price will be to theirs. This means minimizing network latency.

The solution is co-location: run your bot physically close to Hyperliquid's servers.

Hyperliquid's infrastructure is hosted in the Google Cloud europe-west1 region, which is in Belgium. However, for raw server performance and cost, many top teams (including ours) have found that running bots on dedicated servers from Hetzner in Helsinki, Finland provides an exceptional latency profile to Hyperliquid's matching engine. The network path is clean and fast. A cheap VPS from Hetzner will give you a significant edge over a bot running from your home network in the US.

5. The Monitoring Stack: Grafana + Telegram

A bot running in the wild without monitoring is a financial accident waiting to happen. You need to know if it's running, if it's profitable, and if it's throwing errors.

Our go-to stack is simple, effective, and cheap:

  • Prometheus + Grafana: Your bot should expose key metrics (current PnL, number of trades, open positions, error counts) on a /metrics endpoint. Prometheus scrapes this data, and Grafana turns it into beautiful, real-time dashboards. Seeing your PnL on a graph is infinitely more useful than staring at logs.
  • Telegram Alerts: For critical events, you need instant notifications. A simple Python script using the python-telegram-bot library can send you alerts for:
    • Bot started/stopped
    • New trade executed
    • Significant PnL change (e.g., a 5% loss in an hour)
    • Critical errors or WebSocket disconnects

This setup gives you both a high-level overview (Grafana) and immediate, actionable alerts (Telegram).

Putting It All Together: A Real-World Example

This isn't just theory. We use this exact architectural pattern for our production bots. For instance, our RVV Bot (Relative Value of Volatility) is a market-making strategy that constantly places and cancels orders based on volatility signals.

It runs on a dedicated Hetzner server, uses the WebSocket for market data, the SDK for order management, and sends all its PnL and performance metrics to a Grafana dashboard with Telegram alerts for monitoring. The core principles are identical to the copy trading bot described here. You can see its live performance at nexus-bot.pro/rvv.

Building a trading bot is a journey, but the barrier to entry has never been lower. With a platform like Hyperliquid and the right stack, you can go from idea to a functioning core in minutes.

Happy coding, and may your trades be profitable.


I'm a quantitative developer specializing in high-frequency crypto trading strategies. I've packaged the complete, production-ready version of this stack—including deployment scripts, advanced error handling, and risk management modules—into a **Hyperliquid Bot Deployment Kit. You can find it here: https://nexus-bot.pro/courses/hyperliquid-kit/
[tokens: in=221 out=2649 thinking=1736 | cost=$0.0441]

Top comments (0)