
How to Build a Hyperliquid Copy Trading Bot with Python, gRPC, and Dwellir
Copy trading on Hyperliquid lets you mirror proven traders across perpetual markets without building your own trading signals. In this guide, we'll show you how to build a copy trading bot with Python using Dwellir's Hyperliquid gRPC endpoint. You'll learn how the implementation works, how to adapt it to your strategy, and what safety controls to enable before copying a live wallet.
TL;DR: Mirror successful Hyperliquid wallets with Python, gRPC, and Dwellir's managed endpoints. Use Dwellir's HyperEVM, orderbook WebSocket, Hypercore gRPC, and dedicated Execution Environments for fast, reliable infrastructure. Start in dry-run mode with risk controls, then move to production when you're ready.
Dwellir provides managed Hyperliquid infrastructure, including HyperEVM RPC, orderbook WebSocket, Hypercore gRPC, and dedicated nodes so you can focus on your strategy instead of managing infrastructure.
This guide pairs the video walkthrough with code from the repository and implementation details so you can build a working copy trading bot in an afternoon.
What Will You Learn in This Guide?
This tutorial shows you how to build a Hyperliquid copy trading bot that mirrors successful wallets with proper risk controls.
- Build a working copy trader using Python 3.8+, gRPC, and Dwellir's code examples
- Set up risk controls including position sizing, min/max limits, coin filters, and slippage tolerance before placing live orders
- Stream Hyperliquid block fills in real time and copy trades from any wallet address
- Use Dwellir's managed infrastructure instead of running your own nodes
What Hyperliquid Services Does Dwellir Provide?
Dwellir provides managed Hyperliquid infrastructure so you can build trading applications without running your own nodes.
HyperEVM RPC Access HyperEVM smart contracts with the managed HyperEVM RPC endpoint supporting HTTPS, WebSockets, and subscriptions.
Orderbook WebSocket Stream order book depth, trades, and detailed L4 order data via the Hyperliquid orderbook WebSocket with up to 100 levels per side and lower latency than the public feed.
Hypercore gRPC Stream block fills, liquidations, and other Hypercore data using the Hypercore gRPC interface with TLS and API key authentication.
Dedicated Hyperliquid nodes Reserve dedicated infrastructure through the dedicated node service for consistent performance.
Execution Environments Run your trading bots on co-located Execution Environments (VPS) in the same data center as your dedicated node for lower latency.
Why Use Dwellir's Hyperliquid gRPC Endpoint?
Dwellir handles node management and infrastructure so you can connect directly to Hyperliquid data and execution. The gRPC gateway uses the official schema and scales with your needs.
- Managed infrastructure: Dwellir's Hyperliquid endpoint provides the full gRPC gateway with TLS, large message limits, and API key authentication so you can run bots in production without managing nodes. See the Hyperliquid documentation for details.
- Real-time trade data:
StreamBlockFillsdelivers every fill on Hyperliquid with the same schema used by the official SDK, which works well for detecting trades from specific wallets. The streaming reference covers payloads, retry behavior, and metadata options. - Full market coverage: Hyperliquid's perpetual markets include major assets and long-tail tokens, so you can follow wallets trading beyond just BTC and ETH.
How Does the Copy Trading Architecture Work?
The bot is modular so you can add your own analytics, storage, or routing without rewriting everything. Here's how it works:
- gRPC stream: A Python client subscribes to
StreamBlockFillsover TLS to receive every trade as it happens. - Fill processor: The bot filters events to a specific wallet, removes duplicates, and determines if each trade opens or closes a position.
- Position sizing: The bot calculates position size based on your account value, allocation percentage, and min/max limits.
- Order execution: The bot places orders through the Hyperliquid Python SDK with optional slippage tolerance. Closing orders use reduce-only mode.
- Safety controls: Position syncing, coin filters, and dry-run mode let you test the bot before going live.
| Component | What it Does | Dwellir Advantage |
|---|---|---|
| Stream ingestion | Receives every Hyperliquid fill in real time | Managed gRPC endpoint with TLS and large message limits |
| Wallet filter | Filters for trades from the wallet you're copying | Uses Hypercore's standard schema |
| Risk engine | Controls position sizes and exposure | API key authentication for secure access |
| Execution | Places orders to mirror trades | Co-located Execution Environments for lower latency |
| Observability | Tracks performance and uptime | Dedicated nodes with monitoring |
Where Can You Find the Reference Code?
The code for this tutorial is available in the copy-trading-bot folder of Dwellir's public examples repository. Clone it to explore the modules, .env template, and helper utilities.
# Clone the reference implementation
git clone https://github.com/dwellir-public/gRPC-code-examples
cd gRPC-code-examples/copy-trading-bot
pip install -r requirements.txt
The copy_trader.py file contains the full runnable bot, while .env.example captures every tunable variable covered in the video.
How Do You Build the Hyperliquid Copy Trading Bot Step by Step?
Follow these steps in order. Each builds on the last. Test everything in dry-run mode first, then move to production once you're comfortable with the logs and risk controls.
1. Configure Credentials and Risk Limits
Start by copying the sample environment file and updating it with your Dwellir endpoint, Hyperliquid credentials, and risk limits. Dry run mode stays enabled until you explicitly disable it.
cp .env.example .env
HYPERLIQUID_ENDPOINT=hl-yourtenant.n.dwellir.com:443
HYPERLIQUID_API_KEY=dwlr_live_xxxxx
TARGET_WALLET_ADDRESS=0x1234567890abcdef1234567890abcdef12345678
COPY_PERCENTAGE=5.0
MIN_POSITION_SIZE_USD=10
MAX_POSITION_SIZE_USD=150
MAX_OPEN_POSITIONS=6
SLIPPAGE_TOLERANCE_PCT=0.5
DRY_RUN=true
ENABLED_COINS=
- Endpoint & API key: Provided by Dwellir once your Hyperliquid access is approved.
- Target wallet: Choose a wallet from the Hyperliquid leaderboard or a trader you trust, then paste the address. The Hyperliquid leaderboard shows top traders by ROI, PnL, and recent activity.
- Copy percentage: Controls how much of your account value goes into each mirrored trade. Use it with min/max caps to control position sizes.
- Slippage & filters: Prevent bad fills on illiquid markets by setting a slippage tolerance and limiting which coins to trade.
load_dotenv()
self.endpoint = os.getenv('HYPERLIQUID_ENDPOINT')
self.api_key = os.getenv('HYPERLIQUID_API_KEY', '')
self.target_wallet = os.getenv('TARGET_WALLET_ADDRESS', '').strip().lower()
self.copy_percentage = float(os.getenv('COPY_PERCENTAGE', '5.0'))
self.max_position_usd = float(os.getenv('MAX_POSITION_SIZE_USD', '100'))
self.min_position_usd = float(os.getenv('MIN_POSITION_SIZE_USD', '10'))
self.max_open_positions = int(os.getenv('MAX_OPEN_POSITIONS', '4'))
self.slippage_tolerance_pct = float(os.getenv('SLIPPAGE_TOLERANCE_PCT', '0.5'))
This initialization block centralizes configuration, sets sensible defaults, and normalizes the target wallet address. It also keeps credentials in environment variables instead of hardcoded in the code.
2. Connect to the gRPC Stream
The bot's stream_block_fills method handles channel setup, authentication, and the stream loop. This is where trading data enters your bot.
credentials = grpc.ssl_channel_credentials()
options = [
('grpc.max_receive_message_length', 150 * 1024 * 1024),
('grpc.keepalive_time_ms', 10000),
('grpc.keepalive_timeout_ms', 5000),
]
with grpc.secure_channel(endpoint, credentials, options=options) as channel:
client = hyperliquid_pb2_grpc.HyperLiquidL1GatewayStub(channel)
metadata = [('x-api-key', self.api_key)] if self.api_key else []
request = hyperliquid_pb2.Timestamp(timestamp=0)
for response in client.StreamBlockFills(request, metadata=metadata):
block_data = json.loads(response.data.decode('utf-8'))
events = block_data.get('events', block_data)
for wallet, fill in events:
self.process_fill(wallet, fill)
Key details from the implementation:
- The endpoint auto-appends
:443if you omit a port. - Message size is boosted to 150 MB to handle busy blocks without truncation.
- Metadata supports an API key so you can rate-limit or audit access per bot.
- The loop parses both list-style and dict-style responses and hands fills to
process_fillfor business logic.
3. Detect and Validate Target Trades
The process_fill function applies your risk controls. It filters by wallet, removes duplicates, checks position limits, and logs trades before execution.
if wallet_address.lower() != self.target_wallet:
return
fill_id = f"{fill_data.get('hash', '')}_{fill_data.get('tid', '')}"
if fill_id in self.processed_fills:
return
self.processed_fills.add(fill_id)
coin = fill_data.get('coin', '')
direction = fill_data.get('dir', '')
is_closing = direction.startswith('Close')
if not is_closing and len(self.open_positions) >= self.max_open_positions:
print("SKIP: Max positions reached")
return
Fills can repeat in the stream, so the bot combines the fill hash and trade ID to ignore duplicates. The direction field shows whether a trade opens or closes a position, which ensures the bot only sends reduce-only orders when closing positions.
4. Size Positions Responsibly
The bot calculates position sizes using your live account value from the Hyperliquid user_state endpoint when not in dry-run mode. It enforces your percentage allocation and Hyperliquid's $10 minimum order size.
user_state = self.info.user_state(self.wallet_address)
account_value_usd = float(user_state["marginSummary"]["accountValue"])
our_value_usd = account_value_usd * (self.copy_percentage / 100.0)
our_value_usd = min(our_value_usd, self.max_position_usd)
if our_value_usd < self.min_position_usd:
return None
our_size_raw = our_value_usd / float(target_price)
our_size = self._round_size(coin, our_size_raw)
if our_size * float(target_price) < self.min_notional_usd:
return None
With this logic, a $20,000 account with a 5% copy percentage will place roughly $1,000 per trade, but never exceed your min/max caps. For altcoins, rounding uses the native precision (BTC uses five decimals, ETH uses four) so your orders pass validation.
5. Execute Orders with Slippage Control
In live mode, the place_order function places orders using the Hyperliquid Python SDK. It can adjust the price by your slippage tolerance to improve fill rates and syncs positions after each order.
if not is_closing and self.slippage_tolerance_pct > 0:
order_price = order_price * (1 + self.slippage_tolerance_pct / 100) if is_buy else order_price * (1 - self.slippage_tolerance_pct / 100)
order_price = self._round_price(coin, order_price)
order_result = self.exchange.order(
coin,
is_buy,
size,
order_price,
{"limit": {"tif": "Ioc"}},
reduce_only=is_closing,
)
The bot logs errors like partial fills, minimum size violations, and precision issues so you can adjust your configuration. After each successful trade, the bot syncs positions from Hyperliquid to keep its local state accurate.
6. Deploy and Monitor the Bot in Production
Once you're satisfied with dry-run performance, deploy the bot to production. Dwellir customers can run the bot on a dedicated Execution Environment in the same data center as their Hyperliquid node for lower latency. Set up metrics collection (Prometheus, Datadog, Grafana Cloud) to monitor:
- Stream disconnects or slow gRPC responses
- Skipped fills that might indicate minimum size violations
- Differences between target and mirrored positions or PnL
Pro Tip: Use structured logs (JSON format) so you can easily correlate trades with Hyperliquid events and replay decision logic when reviewing performance.
How Can You Extend the Copy Trading Strategy?
Think of the base bot as a starting point. You can add analytics, monitoring, and portfolio management to improve results before deploying larger capital.
- Leaderboard research: Use the Hyperliquid leaderboard to find wallets with consistent performance, then check their trade history to understand their strategy before copying.
- Portfolio segmentation: Run multiple bot instances with different
.envfiles to allocate different percentages across traders or asset types. - Alerting: Send logs to your monitoring system or add a webhook to get notifications when the bot opens positions or encounters errors.
- Backtesting: Run in
DRY_RUN=truewhile logging every trade decision to a CSV, then analyze results to validate the strategy across multiple wallets. - Coin filters: Start with major assets (BTC, ETH) while you learn, then gradually add altcoins to avoid unexpected losses.
What Should You Verify Before Going Live?
Run through this checklist every time you change configuration. This protects you from issues like stale credentials, insufficient margin, or missing environment variables.
- Confirm your Dwellir Hyperliquid endpoint and API key are active and reachable over TLS
- Run the bot in dry-run mode for at least 24 hours to observe behavior on your target wallet
- Validate that min/max limits align with your account size and Hyperliquid's $10 minimum
- Double-check that private keys never leave your secure environment and are not committed to version control
- Monitor available margin on Hyperliquid to prevent liquidation or failure to mirror closes
Hyperliquid Copy Trading FAQ
Common questions about building copy trading bots on Hyperliquid.
Is this really no-code?
You don't have to write new Python to get started. Just update the environment variables in the .env file. But you should read through the code to understand how risk controls work. The repo is designed to be easy to extend if you want to customize it.
How fast is the data feed?
The gRPC stream delivers trades as soon as they finalize on Hyperliquid. Dwellir's infrastructure keeps latency low so your orders can execute at similar price levels before the market moves.
Can I copy multiple wallets at once?
Yes. Run separate processes or containers with different .env files. Watch your total exposure across all bots. Use max position counts and copy percentages to manage capital allocation.
What happens if the target wallet closes a trade I never filled?
The bot syncs positions from Hyperliquid before sending reduce-only orders. If it can't find the position, it skips the close to avoid opening a reverse position. The bot logs this so you can review it manually.
Where can I get Hyperliquid data without running my own node?
Dwellir provides managed Hyperliquid infrastructure including HyperEVM RPC, orderbook WebSockets, Hypercore gRPC, and dedicated nodes so you can connect through authenticated APIs instead of managing infrastructure.
What Should You Do Next?
Here's how to go from tutorial to production:
- Contact Dwellir to get access to Hyperliquid gRPC streaming for your copy trading bot.
- Clone the copy trading bot repository, test it in dry-run mode, and adjust the
.envfile for your wallet and risk tolerance. - Consider pairing this bot with a real-time liquidation tracker to monitor market conditions alongside your copied trades.
Ready to start building? For Hyperliquid gRPC access, contact our team. For HyperEVM RPC, sign up at our dashboard. Check out the Hyperliquid documentation for implementation details and API references.
This guide and the accompanying video are for educational purposes only and do not constitute financial advice. Trading cryptocurrencies and derivatives involves significant risk of loss. Always conduct your own research and never trade with funds you cannot afford to lose.
read another blog post