Home>Blog>Your Copy Trading Bot Will Break. Here's How to Build One That Doesn't.
Your Copy Trading Bot Will Break. Here's How to Build One That Doesn't.

Your Copy Trading Bot Will Break. Here's How to Build One That Doesn't.

By CMM Team - 08-Jul-2026

Your Copy Trading Bot Will Break. Here's How to Build One That Doesn't.

Building a copy trading bot on Hyperliquid takes an afternoon. The polling loop is maybe 50 lines of Python: fetch a wallet's positions, compare them to your local state, mirror the delta. Every open-source implementation on GitHub follows roughly the same pattern, and most of them work fine in the first week of testing.

Then one of five things happens. The lead wallet closes a position between your poll intervals, and you hold a stale trade through a liquidation cascade. The wallet you're copying hedges on another venue, so what looks like a directional bet is actually one leg of a neutral position. Or the wallet's leverage makes sense for a $3M account but creates a margin call on your $10K account, because your bot copied the direction without adjusting the size.

The polling loop is not the hard part. The risk layer around it is the part that takes months to get right, and it's the part most tutorials skip entirely.

This guide covers the four-layer architecture for a copy trading bot that handles the structural failure modes, with concrete code for Hyperliquid's onchain infrastructure and HyperTracker's cohort intelligence API. If you've already built the basic loop and watched it fail in production, this is the missing layer.

Why Hyperliquid is the best venue for copy trading

Copy trading requires transparent position data. On a centralized exchange, you only get copy trading if the exchange builds it as a feature, curates "lead traders," and gives you access to their positions through a proprietary system. On Hyperliquid, every position is onchain and queryable by default. You do not need the exchange's permission to see what any wallet is doing.

Hyperliquid's fully onchain central limit order book processes around 200,000 orders per second. Every fill, every cancel, every position change is a verifiable chain event. For copy trading specifically, this means two things: you can poll any wallet's positions without needing an API key from the exchange, and you can verify that your bot's execution actually happened onchain rather than trusting an off-chain matching engine.

The minimum order size on Hyperliquid is $10 notional. This is relevant because proportional sizing on a small account can produce trade sizes that fall below this floor. Your bot needs to handle this gracefully: skip the trade, log it, and move on.

The four-layer architecture

A copy trading bot that survives live trading has four distinct layers. Each one can fail independently, which means each one needs its own error handling and logging.

Copy Bot Architecture

Layer 1: Wallet discovery

The quality of a copy trading system depends entirely on wallet selection. A flawless execution engine mirroring a bad wallet will lose money with perfect fidelity. The discovery layer filters the entire Hyperliquid ecosystem down to a handful of wallets worth following.

Start with the leaderboard. HyperTracker's /leaderboards/perp-pnl endpoint ranks wallets by cumulative perp PnL across all-time, monthly, weekly, and daily timeframes. All-time PnL is the most reliable filter because it captures performance across multiple market regimes, which separates sustained edge from a lucky week.

Then filter by cohort. HyperTracker classifies every wallet on Hyperliquid into one of 16 behavioral cohorts: 8 by account size (Shrimp through Leviathan) and 8 by all-time PnL (Giga-Rekt through Money Printer). For copy trading, the Money Printer cohort (all-time PnL above $1M, segment ID 8) and Smart Money cohort ($100K to $1M, segment ID 9) are the two segments where sustained profitability is most likely to reflect genuine trading skill rather than variance.

import requests

API_BASE = "https://ht-api.coinmarketman.com/api/external"
headers = {"Authorization": "Bearer YOUR_JWT_TOKEN"}

# Smart Money wallets with open positions, sorted by PnL
response = requests.get(
    f"{API_BASE}/wallets",
    headers=headers,
    params={
        "segmentIds": 9,
        "hasOpenPositions": True,
        "orderBy": "perpPnl",
        "order": "desc",
        "limit": 20,
    },
)
candidates = response.json()

After pulling candidates, check activity frequency. A wallet that trades once a month generates too few signals to be useful. A wallet that opens dozens of positions daily generates too much noise and your execution costs will eat any edge. The useful range for copy trading is wallets that take a few positions per week with clear entries and defined holding periods.

Layer 2: Position monitoring

The monitoring layer polls each target wallet's positions at a regular interval and detects changes. Five minutes is the standard cadence for non-HFT copy trading. Faster polling catches entries earlier but increases API costs and adds noise from partial fills that have not settled. Slower polling misses short-lived positions and increases exit timing drift.

Polling Loop Flow

The diff engine is the core of this layer. Each poll cycle, it compares the remote wallet's current positions against your local snapshot and produces a set of events: OPEN (new position appeared), INCREASE (existing position grew), REDUCE (existing position shrank), and CLOSE (position gone). Each event type needs different handling in the execution layer.

def diff_positions(local_state, remote_positions):
    events = []
    remote_map = {p["coin"]: p for p in remote_positions}
    local_map = {p["coin"]: p for p in local_state}

    for coin, pos in remote_map.items():
        if coin not in local_map:
            events.append({"type": "OPEN", "coin": coin, "position": pos})
        elif abs(float(pos["szi"]) - float(local_map[coin]["szi"])) > 0.001:
            if abs(float(pos["szi"])) > abs(float(local_map[coin]["szi"])):
                events.append({"type": "INCREASE", "coin": coin, "position": pos})
            else:
                events.append({"type": "REDUCE", "coin": coin, "position": pos})

    for coin in local_map:
        if coin not in remote_map:
            events.append({"type": "CLOSE", "coin": coin, "position": local_map[coin]})

    return events

Layer 3: The risk gate

This is the layer most tutorials skip, and it's the one that determines whether your bot survives live trading. The risk gate sits between the monitoring layer and the execution layer. It receives trade signals and either approves them, modifies them, or vetoes them entirely.

Proportional sizing. The most common copy trading failure is a size mismatch. If the lead wallet has $3M in equity and opens a position worth $300K, that is a measured allocation for them. If your bot mirrors the same dollar amount on a $10K account, you are 30x leveraged on a single trade. Proportional sizing scales the position to your account's equity ratio:

def calculate_copy_size(lead_size, lead_equity, my_equity):
    ratio = my_equity / lead_equity
    scaled = lead_size * ratio
    # Hyperliquid minimum notional is $10
    if scaled * current_price < 10:
        return None  # Skip: below minimum
    return scaled

Leverage cap. Even with proportional sizing, the lead wallet may be using leverage that exceeds your risk tolerance. Your bot should enforce a per-asset leverage ceiling independently of whatever the lead wallet uses. If the signal calls for 20x but your cap is 5x, the risk gate reduces the size accordingly or skips the trade.

Exposure limit. A single position should not consume your entire account. Set a maximum percentage of equity per trade. When the risk gate receives a signal that would exceed this limit, it either scales down or vetoes.

Circuit breaker. If your account equity drops below a threshold in a single session, the bot should stop opening new positions. This is the kill switch that prevents a cascading loss from compounding into a liquidation. It does not close existing positions (that would lock in losses during a temporary drawdown). It simply pauses new entries until you manually review.

Layer 4: Execution

The execution layer translates approved signals into orders on Hyperliquid using the official Python SDK. The key function is exchange.order(), which takes the asset, direction, size, price, and order type.

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

info = Info(constants.MAINNET_API_URL, skip_ws=True)
exchange = Exchange(wallet, constants.MAINNET_API_URL)

# Place a market buy order for ETH
result = exchange.order(
    coin="ETH",
    is_buy=True,
    sz=0.5,
    px=None,  # market order
    order_type={"limit": {"tif": "Ioc"}},  # IOC for market-like execution
)

After execution, the bot needs to verify the fill. The SDK returns a status object with either resting (order placed on the book) or filled (immediate fill with average price). For copy trading, you want IOC (immediate-or-cancel) orders in most cases, because the point is to match the lead wallet's position now, not to wait for a specific price.

Log every execution with the lead wallet's entry price, your entry price, the time delta between detection and fill, and the slippage. This log becomes the diagnostic tool for tuning the system later.

The five failure modes (and how to handle each)

Failure Modes

Every copy trading bot built from a basic polling loop is vulnerable to the same five structural failures. These are not bugs. They are design limitations that require architectural solutions.

Hidden hedging. The lead wallet opens an ETH long on Hyperliquid and an ETH short of the same size on another venue. Their net exposure is zero. Your copy is a naked long. When ETH drops, they lose nothing and you lose everything. There is no way to detect this from onchain data alone, because the hedge exists on a different chain or a centralized exchange. The mitigation is to use cohort-level signals instead of single wallets. When the entire Smart Money cohort shifts net long on ETH, that is a consensus signal from hundreds of wallets. They cannot all be hedging at the same time.

Signal decay. As a wallet becomes popular for copy trading, more bots pile in on the same signal. The lead wallet enters at $3,500. By the time your bot detects and executes, the price has moved to $3,512 because other copy traders already bought. This slippage compounds on every trade and erodes edge over time. Monitor your entry price versus the lead wallet's fill price. If slippage consistently exceeds a threshold, the wallet is too crowded to copy profitably.

Size mismatch. Already covered in the risk gate section. Proportional sizing and an independent leverage cap are the core defense.

Exit timing drift. The lead wallet closes a position between your poll intervals. You miss the exit signal and hold a stale position. If the position reverses during that gap, you eat a loss that the lead wallet avoided. Tighten your poll interval for wallets with active positions (poll every minute when a copied position is live, every five minutes when idle). Set independent trailing stops on your own positions as a backstop.

Survivorship bias. The leaderboard shows wallets that are profitable right now. It does not show the thousands of wallets that followed similar strategies and blew up. A wallet with $2M in all-time profit may have gotten there through aggressive leverage that will eventually mean revert. Filter by trade count (minimum hundreds of trades) and look at drawdown relative to total PnL. A high-PnL wallet with massive drawdowns is a worse copy target than a moderate-PnL wallet with a smooth equity curve.

Cohort signals as a safer alternative

Single-wallet copy trading is a sample size of one. You are betting that one address has persistent edge, is not hedging elsewhere, and will continue to trade in a pattern your bot can follow. Every assumption in that chain can break.

Cohort-level signals aggregate positioning across hundreds of wallets with the same profitability profile. When our data shows the Money Printer cohort shifting net long on BTC while the Giga-Rekt cohort (all-time PnL below -$1M, segment ID 15) is going net short on the same asset, that divergence is a statistically meaningful signal. One wallet can be wrong or hedging. An entire profitability cohort acting in concert is a different kind of information.

HyperTracker's /cohort-metrics endpoint gives you aggregate positioning by segment, refreshed every 5 minutes. You can build a system that monitors cohort bias rather than individual wallets, which eliminates the hidden hedging problem, reduces signal decay (no single address to crowd), and provides a diversified signal source.

# Fetch Smart Money cohort metrics for BTC
cohort_data = requests.get(
    f"{API_BASE}/cohort-metrics",
    headers=headers,
    params={"coin": "BTC", "segmentId": 9},
).json()

# Check net bias: are Smart Money wallets net long or short?
net_bias = cohort_data.get("netBias")

The tradeoff is precision. Cohort signals tell you that smart money is accumulating, but they do not tell you the entry price, the leverage, or the exact timing. You use cohort signals for directional bias and manage your own entries through technical levels, limit orders, or DCA.

Running a dry run before going live

Deploy with real-time data and simulated execution for at least two weeks before committing capital. The dry run reveals problems that backtesting cannot: API rate limits under production load, edge cases in the diff engine when Hyperliquid lists a new asset, and fill simulation accuracy.

Log every simulated trade with the price at detection, the price at simulated fill (you can use the mid-price as a proxy), and the outcome if you had actually executed. Track win rate, average slippage, and max drawdown across the dry run period. If the simulated results do not match your backtest assumptions within a reasonable margin, the gap is usually in execution: slippage, timing, or position sizing edge cases the backtest did not capture.

Several open-source Hyperliquid copy trading bots support dry mode out of the box. The Python-based bots typically implement this as a simulated balance tracker that processes real signals without submitting orders, which lets you validate the entire pipeline from wallet discovery through risk gate to execution logic without risking capital.

Build your copy trading system with cohort intelligence

HyperTracker's API gives you the leaderboard data, cohort filtering, and aggregate positioning metrics that power the wallet discovery and signal layers. Start with the free tier (100 requests/day) and scale to Pulse ($179/mo) when you're ready for production polling cadences.

Get your API key

The architecture matters more than the signal

Most copy trading bot guides focus on the signal: which wallet to follow, which trades to copy. The signal is maybe 10% of the system. The architecture around it is the other 90%. The risk gate, the position sizing logic, the circuit breaker, the exit timing handler, the slippage monitor, the dry run framework. These are the components that determine whether the bot survives its first drawdown or liquidates your account on a Tuesday afternoon.

Build the risk layer first. Test it with extreme inputs. Then add the signal on top. The best copy trading bot is the one that knows when to do nothing.