How to backtest a Hyperliquid strategy with backtrader (Python)
Updated Nov 18, 2026 · 5 min read
Pull Hyperliquid candles from the public info API, run them through backtrader with the 0.045% base-tier taker fee and slippage, and read the results. Tested with backtrader 1.9.78.123 on Nov 18, 2026.
How do you backtest a Hyperliquid strategy with backtrader? Pull candles from Hyperliquid’s public info API (no key needed), pass them to bt.feeds.PandasData, and charge 0.045% per fill (Hyperliquid’s base-tier taker fee on crypto perps) plus a slippage assumption. backtrader only backtests here: it has no Hyperliquid connection. The script below ran on Nov 18, 2026 with backtrader 1.9.78.123, pandas 3.1.1 and Python 3.12.
Key takeaways
- backtrader’s latest release, 1.9.78.123, dates from Apr 19, 2023, but it still ran on Python 3.12.
- Allow fractional sizes, or backtrader rounds a BTC order down to zero.
- In our run, a 0.045% fee and 0.05% slippage cut a 20/50 SMA crossover from +19.8% to +8.8%.
Is backtrader still maintained?
backtrader is a GPL-3.0 Python framework for backtesting and live trading. Its latest PyPI release, 1.9.78.123, was uploaded on Apr 19, 2023; the newest commit on master is that day’s version bump, and issues are switched off on GitHub. It still installed and ran on Python 3.12.
The backtest script
Hyperliquid’s info endpoint answers a candleSnapshot request with only the most recent 5,000 candles per interval, so 4h BTC reaches back to Aug 2024; for more history, save candles on a schedule (Hyperliquid historical data). The strategy goes long at 1x when the 20-candle simple moving average crosses above the 50 and exits on the cross back. backtrader fills a market order at the next candle’s open, and set_slippage_perc moves that price against you. Its default commission scheme rounds order sizes down to whole units, which turns a $9,500 BTC order into zero, so PerpFee returns fractional sizes and charges the fee as a fraction of trade value on every fill.
# Pull Hyperliquid BTC 4h candles (public info API, no key) and backtest an SMA 20/50 crossover in backtrader with fees and slippage.
import json, time, urllib.request
import backtrader as bt
import pandas as pd
TAKER_FEE = 0.00045 # 0.045% per fill: Hyperliquid base-tier taker fee, crypto perps
SLIPPAGE = 0.0005 # 0.05% per fill: our assumption, not a Hyperliquid number
def fetch_candles(coin="BTC", interval="4h", bar_ms=4 * 3600 * 1000):
now = int(time.time() * 1000)
body = {"type": "candleSnapshot",
"req": {"coin": coin, "interval": interval, "startTime": now - 5000 * bar_ms, "endTime": now}}
req = urllib.request.Request("https://api.hyperliquid.xyz/info", json.dumps(body).encode(),
{"Content-Type": "application/json"})
df = pd.DataFrame(json.load(urllib.request.urlopen(req)))[["t", "o", "h", "l", "c", "v"]].astype(float)
df.columns = ["time", "open", "high", "low", "close", "volume"]
df["time"] = pd.to_datetime(df["time"], unit="ms") # UTC
closed = df["time"] + pd.Timedelta(interval) <= pd.Timestamp.now("UTC").tz_localize(None)
return df[closed].set_index("time") # drop the candle still open
class PerpFee(bt.CommissionInfo):
"""Fee as a fraction of trade value on every fill, and fractional sizes (the default rounds to whole units)."""
def getsize(self, price, cash):
return self.p.leverage * cash / price
class SmaCross(bt.Strategy):
params = dict(fast=20, slow=50)
def __init__(self):
self.cross = bt.ind.CrossOver(bt.ind.SMA(period=self.p.fast), bt.ind.SMA(period=self.p.slow))
def next(self):
if not self.position and self.cross > 0:
self.order_target_percent(target=0.95) # long, 1x, cash buffer for fees
elif self.position and self.cross < 0:
self.close()
def run(df, fee, slip):
cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.PandasData(dataname=df, timeframe=bt.TimeFrame.Minutes, compression=240))
cerebro.addstrategy(SmaCross)
cerebro.broker.setcash(10_000)
cerebro.broker.addcommissioninfo(PerpFee(commission=fee))
if slip:
cerebro.broker.set_slippage_perc(slip) # market orders fill at the next open, moved against you
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades")
cerebro.addanalyzer(bt.analyzers.DrawDown, _name="dd")
s = cerebro.run()[0]
t = s.analyzers.trades.get_analysis()
closed, won = t.get("total", {}).get("closed", 0), t.get("won", {}).get("total", 0)
return closed, won, cerebro.broker.getvalue() / 10_000 - 1, s.analyzers.dd.get_analysis().max.drawdown
df = fetch_candles()
print(f"backtrader {bt.__version__} | pulled {pd.Timestamp.now('UTC'):%Y-%m-%d %H:%M} UTC: {len(df)} closed 4h candles, "
f"{df.index[0]:%Y-%m-%d %H:%M} to {df.index[-1]:%Y-%m-%d %H:%M} UTC | "
f"buy and hold {df.close.iloc[-1] / df.close.iloc[0] - 1:+.1%}")
for label, fee, slip in [("No costs", 0, 0), ("Taker fee", TAKER_FEE, 0), ("Fee + slippage", TAKER_FEE, SLIPPAGE)]:
closed, won, ret, mdd = run(df, fee, slip)
print(f"{label:15} trades {closed} (won {won}) | return {ret:+.1%} | max drawdown {mdd:.1f}%")| Costs per fill | Trades (won) | Return | Max drawdown |
|---|---|---|---|
| None | 54 (24) | +19.8% | 31.9% |
| 0.045% taker fee | 54 (24) | +14.4% | 32.7% |
| 0.045% fee + 0.05% slippage | 54 (24) | +8.8% | 33.6% |
Costs took 11 points of return over 108 fills and left the rule behind buy and hold. The test also leaves out funding, which Hyperliquid pays every hour, and one market with one parameter pair proves little: test other periods and parameters and resample the trades (how to backtest a crypto strategy, Monte Carlo backtests).
Going live: backtrader doesn’t connect to Hyperliquid
backtrader’s live stores cover Interactive Brokers, Oanda and Visual Chart; it has no Hyperliquid or CCXT store. To trade the rule, rewrite it with CCXT or Hyperliquid’s official hyperliquid-python-sdk (0.24.0, MIT), signing with an API wallet, or move it to Freqtrade, which supports Hyperliquid and has a dry-run mode.
Or run the rule on Senpi
On Senpi, a strategy you confirm runs as code on Senpi’s runtime, and by default no AI model makes live trading decisions. Senpi doesn’t run backtests; Simulations, paper trading with simulated money, are coming. Hyperliquid charges 0.015% maker and 0.045% taker at the base tier on crypto perps. Senpi adds 0% on paid plans (from $50 a month) and 0.03% on the free trial.
Can backtrader trade live on Hyperliquid?
Not natively: its live stores are Interactive Brokers, Oanda and Visual Chart. Rewrite the rule with CCXT or Hyperliquid’s Python SDK to trade it.
Where do I get Hyperliquid data for backtrader?
Send a candleSnapshot request to the public info API at https://api.hyperliquid.xyz/info; no key is needed. Only the latest 5,000 candles per interval are served.
What fee should a Hyperliquid backtest use?
At the base tier on crypto perps, 0.045% for taker fills and 0.015% for maker fills. Higher 14-day volume lowers both.
Sources: backtrader on PyPI, GitHub and backtrader.com; Hyperliquid docs (info endpoint, fees, funding); hyperliquid-python-sdk on PyPI; Freqtrade docs. Checked and run Nov 18, 2026.
This is educational material, not financial advice. Leveraged perps can lose money quickly.
Run a rule without a server
Describe the rule; Senpi runs it on its runtime with a stop from the first fill.
Related articles
What is revenge trading, and how do you stop it?
Revenge trading is trading bigger or faster to win back a loss. Why it happens, the recovery maths that makes it costly, what Hyperliquid data shows, and rules that stop it.
What is the Calmar ratio, and what is a good one?
The Calmar ratio divides annual return by max drawdown. Formula, how to read it, and the one-year Calmar ratio of BTC, ETH, SOL, HYPE, XRP and DOGE on Nov 18, 2026.
How to read Hyperliquid market data: open interest, long/short ratio, funding and liquidations
What open interest, the long/short ratio, funding and liquidations tell you on Hyperliquid, where each number comes from, and how to read them together, with the ten largest perps on Nov 10, 2026.
What is a trailing stop loss, and how do you set one on Hyperliquid?
A trailing stop follows price up and locks in part of the move. Definition, how wide to set it, and BTC, ETH, SOL and HYPE trail sizes on Nov 18, 2026.