Hyperliquid Backtest: How to Test a Strategy in Python
Backtest a Hyperliquid strategy in Python with free historical candles and funding, real fee tiers and slippage, and no look-ahead bias.

A Hyperliquid backtest replays your trading rules over past perp data to measure what a strategy keeps after costs. Ideas that look profitable on a chart fail once you charge 0.09% round-trip taker fees, hourly funding and book slippage.
Bot builders and quants run this check before placing a first live order. Because every order, cancel, trade and liquidation on Hyperliquid happens on-chain, you can test on real public history instead of exchange-curated samples.
Below, you will load hourly BTC bars and funding in Python, charge tier-0 fees and slippage, and test an out-of-sample split.
For the DuckDB download timing, slippage percentiles and crossover P&L behind every Python script below, jump to Test and Validation.
Hyperliquid backtest data at a glance
A perp backtest needs more than prices. Four inputs move your P&L on Hyperliquid:
| Input | Why it matters | Source |
|---|---|---|
| Candles (OHLCV) | Entry and exit prices | Reservoir 1-second candles; native candleSnapshot forrecent bars |
| Funding rates | Paid or received every hour (one eighth of the 8-hour rate) | Native fundingHistory |
| Fees | Charged per fill (0.045% per side, or 0.09% round trip, at tier 0) | Hyperliquid's published fee tiers |
| Slippage | The gap between the chart price and your fill | Reservoir minute order books, or Hydromancer slippageHistory (paid) |
Hyperliquid's free candleSnapshot returns only the latest 5,000 candles per interval, which covers about 7 months of hourly bars but just 3.5 days of 1-minute bars. That is enough for short hourly or daily tests.
For minute-level backtests or deeper history, use Reservoir, Hydromancer's free S3 archive holding every fill since 28 July 2025 and 1-second candles since 31 July 2025. You pay only AWS requester-pays transfer charges.
The same workflow also covers HIP-3 markets deployed by outside teams tracking stocks, indexes and commodities. Reservoir stores each venue's candles and fills in its own folder, though HIP-3 fees can differ from Hyperliquid's own markets.
How to run a Hyperliquid backtest in Python
A complete backtest takes six steps. The first four load candles and funding and price fees and slippage; the last two run the simulation and check it out of sample.
Step 1: Load hourly candles from Reservoir
Roll 1-second candles up to the bar size your strategy trades, then save the Parquet file locally so you query S3 only once. This query builds two months of hourly BTC bars.
Install DuckDB (pip install duckdb) and configure AWS credentials, folders and requester-pays access using How to Query Reservoir's Hyperliquid Data. If you signed in with aws login, run eval "$(aws configure export-credentials --format env)" in the same shell so DuckDB reads the session.
# Expected output: the first 3 of ~1,464 hourly BTC bars (Sep-Oct 2026)
import duckdb
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs;")
con.execute("""
CREATE SECRET (TYPE s3, PROVIDER credential_chain, REGION 'ap-northeast-1');
SET s3_requester_pays = true;
""")
src = "s3://hydromancer-reservoir/by_dex/hyperliquid/candles/1s/date=2026-"
con.execute(f"""
COPY (
SELECT time_bucket(INTERVAL 1 hour, timestamp) AS hour,
arg_min(open, timestamp) AS open, max(high) AS high, min(low) AS low,
arg_max(close, timestamp) AS close, sum(volume) AS volume
FROM read_parquet(['{src}09-*/candles.parquet', '{src}10-*/candles.parquet'])
WHERE coin = 'BTC' AND asset_class = 'perp'
GROUP BY hour ORDER BY hour
) TO 'btc_1h.parquet' (FORMAT parquet)
""")
con.sql("SELECT * FROM 'btc_1h.parquet' LIMIT 3").show()Across September and October 2026, this query wrote 1,464 hourly BTC bars from 61 daily files, downloading about 1.19 GB from S3 in 86 seconds. From that point on, every backtest iteration reads the small local file.
A month of 1-minute BTC bars pulls about 590 MB from S3, inside AWS's free 100 GB monthly transfer tier. Check for gaps: quiet periods have no candle, and the Reservoir guide example found 8 empty minutes in a month of BTC bars.
Step 2: Add Hyperliquid's hourly funding payments
Hyperliquid computes an 8-hour perp funding rate and pays one eighth of it every hour, according to its funding docs. Positive rates mean longs pay shorts, and negative rates mean shorts pay longs.
Skip funding and any strategy holding positions across hours shows distorted returns. Hyperliquid's free fundingHistory endpoint returns one coin's hourly rates, oldest first, up to 500 rows per call, so page forward from the last row's timestamp.
# Expected output: about 1,464 hourly BTC funding rows, then the first 3
import requests
import pandas as pd
start = int(pd.Timestamp("2026-09-01", tz="UTC").timestamp() * 1000)
end = int(pd.Timestamp("2026-11-01", tz="UTC").timestamp() * 1000)
rows = []
while start < end:
r = requests.post("https://api.hyperliquid.xyz/info", json={
"type": "fundingHistory", "coin": "BTC",
"startTime": start, "endTime": end}, timeout=10)
r.raise_for_status()
page = r.json()
if not page:
break
rows += page
start = page[-1]["time"] + 1
funding = pd.DataFrame(rows)
funding["hour"] = pd.to_datetime(funding.time // 3_600_000, unit="h", utc=True)
funding["rate"] = funding["fundingRate"].astype(float)
print(len(funding), funding.head(3))The official docs define each hourly payment as position_size * oracle_price * funding_rate, using the oracle price rather than the mark price. Using your bar price is a close approximation for most tests; see Hyperliquid funding rates for full mechanics.
Step 3: Charge Hyperliquid fees from your actual tier
Hyperliquid charges fees per fill based on rolling 14-day volume. At base tier 0, perps cost 0.045% for takers and 0.015% for makers, so a round-trip taker trade costs 0.09% before funding and slippage.
Higher volume tiers lower those rates, staking HYPE adds a discount, and HIP-3 markets can carry deployer fees or growth-mode reductions. See Hyperliquid fees explained for tiers, discounts and HIP-3 rates.
Use the rate your account actually pays, or default to tier 0 so the test errs against you. Assume taker fees unless your strategy rests limit orders, because maker fills in a backtest also assume your order would have filled.
Step 4: Estimate slippage against Hyperliquid's order book
A market order fills against the book, not at the chart price, and larger orders walk deeper through resting liquidity. Leave slippage out and fast strategies look profitable on paper while bleeding live.
You have three ways to model book impact:
• Fixed basis points per side: add a flat cost per fill as a simple first pass on liquid markets.
• Reservoir L2 order books: walk 1-minute, 20-level snapshots (from 15 December 2025 for Hyperliquid perps and spot) using the method in Hyperliquid slippage.
• Hydromancer slippageHistory: pull 15-minute buy and sell slippage estimates in basis points for fixed sizes from $1K to $1M across every perp market, including HIP-3.
The slippageHistory endpoint requires a paid API key, read below from the HYDROMANCER_API_KEY environment variable.
# Expected output: median and p90 buy slippage in bps, $10K BTC, Sep 2026
import os
import requests
import pandas as pd
start = int(pd.Timestamp("2026-09-01", tz="UTC").timestamp() * 1000)
key = os.environ["HYDROMANCER_API_KEY"]
r = requests.post("https://api.hydromancer.xyz/info",
headers={"Authorization": f"Bearer {key}"},
json={"type": "slippageHistory", "coin": "BTC",
"amount": 10000, "startTime": start, "limit": 2000},
timeout=30)
r.raise_for_status()
slip = pd.DataFrame(r.json())
print(slip["buySlippageBps"].median(), slip["buySlippageBps"].quantile(0.9))Across 2,000 samples from 1 September 2026, $10,000 BTC buys showed 0.06 bps median and 0.17 bps p90 slippage, well under a 2 bps placeholder.
Use a high percentile, not the median, if your strategy trades during fast moves. That is exactly when resting books thin out.
Step 5: Run the backtest without look-ahead bias
Look-ahead bias happens when a strategy uses information it could not have known at the moment it traded. The rule that prevents most of it is simple: decide on a bar's close, and act on the next bar's open.
The moving-average crossover below is chosen only because it is easy to read, not as a trading recommendation. Run it in the same Python session as Steps 1 and 2, with pandas and pyarrow installed, so it reads btc_1h.parquet and funding.
Reservoir returns prices as DECIMAL values, so the script casts open and close to floats before doing math.
# Expected output: in- and out-of-sample lines (illustrative only)
import pandas as pd
bars = pd.read_parquet("btc_1h.parquet")
bars[["open", "close"]] = bars[["open", "close"]].astype(float) # DECIMAL
bars = bars.merge(funding[["hour", "rate"]], on="hour", how="left")
TAKER_FEE = 0.00045 # tier 0 perp taker fee, 0.045%
SLIPPAGE = 0.0002 # 2 bps per side; replace with your own estimate
def backtest(df, fast=24, slow=96):
signal = df.close.rolling(fast).mean() > df.close.rolling(slow).mean()
pos = signal.astype(int).shift(1).fillna(0) # held from next open
bar_ret = df["open"].shift(-1) / df["open"] - 1 # this open to next open
gross = (pos * bar_ret).sum()
trades = pos.diff().abs().fillna(pos.abs())
costs = (trades * (TAKER_FEE + SLIPPAGE)).sum()
fund = (pos * df["rate"].shift(-1)).sum() # paid at this bar's end
return int(trades.sum()), gross, costs, fund, gross - costs - fund
cut = bars["hour"] < pd.Timestamp("2026-10-01", tz="UTC") # True: in-sample
for name, part in [("in-sample", bars[cut]), ("out-of-sample", bars[~cut])]:
n, gross, costs, fund, net = backtest(part)
print(f"{name}: {n} trades, gross {gross:.2%}, costs {costs:.2%},",
f"funding {fund:.2%}, net {net:.2%}")On the September-October 2026 BTC dataset, this crossover printed +0.66% net in-sample vs -9.07% net out-of-sample after fees, slippage and hourly funding. Those lines confirm the cost accounting; they are not a strategy to trade.
Returns here are summed rather than compounded, which is fine for comparing variants. Each split restarts the moving averages, so the first 96 hours of each have no position.
Funding is paid at the end of each hour, so the rate stamped 14:00 applies to the position held from 13:00 to 14:00. That is why the code pairs each bar with the next row's rate via shift(-1).
A position still open at the end of a period is not closed, so its exit fee and slippage are omitted. Add a closing trade if your rule can finish a split in a position.
Look-ahead bias can also hide in bar labels, daily snapshots and funding timing. Each trap is covered under What to know before you trust a Hyperliquid backtest.
Step 6: Test the strategy out of sample
Every parameter you tune on a historical period makes that period look better. If you test 50 moving-average combinations and keep the best, you have mostly measured luck.
Split your history by time, never at random. Tune on the earlier slice, then run once on the later slice without changing anything.
For stronger confidence, walk forward: tune on months one to three, test on month four, then roll the window ahead. Log every variant you tried, because one honest out-of-sample run after costs beats a polished in-sample curve.
Hyperliquid API vs Hydromancer for backtest data
For most backtests you don't need to pay for data, and we'd rather say so. Reservoir's free candles and fills plus Hyperliquid's free fundingHistory already cover the core inputs.
Hyperliquid's native API covers recent candles and funding history, while Hydromancer adds deeper and finer history through Reservoir (free) and paid endpoints (starting at $300 a month for live REST and WebSocket API keys).
| You need | Hyperliquid API | Hydromancer |
|---|---|---|
| Candles older than the latest 5,000 | Not available:candleSnapshot keeps thelatest 5,000 per interval | Reservoir 1-second candles from 31 Jul 2025 (free, AWS requester pays), or candleSnapshot (API key) |
| Funding rates | fundingHistory, free | fundingHistory from 28 Jul2025 (API key, paid plan) |
| Slippage by order size | No history; model it yourself | Reservoir minute order books (free), or slippageHistory15-minute samples (API key, paid plan) |
| Every trade, for tick-level tests | Not available from the native API | Reservoir fills from 28 Jul 2025 (free, AWS requester pays) |
| The current day's bars | candleSnapshot, free,1 minute and up | candleSnapshot down to 1second (API key, paid plan) |
| Fits | Hourly or daily tests over a few months | Minute-level or longer tests, slippage and tick data |
For a broader overview of data sources, see How to get Hyperliquid data and the historical data page.
What to know before you trust a Hyperliquid backtest
A test that passes can still be wrong in ways its summary line will not show.

A bar's label is its start, not its end
When you roll 1-second candles into hourly bars, each bar is labeled with the hour it starts. A bar labeled 14:00 holds 14:00 to 14:59, so its close is not known until 15:00.
Hyperliquid's native candles carry both times: t is the open time and T is the close time. Base each decision on the close time.
Reservoir's daily snapshots are taken after midnight UTC
Reservoir's position snapshots are taken once a day, a few minutes after midnight UTC. A snapshot shows positions at that moment, so a test can only use it from that time on.
Each file's name includes the block and time it was taken. Check both before matching a snapshot to a trade.
An hour's funding rate isn't known until the hour ends
Hyperliquid samples the premium every 5 seconds and averages it over the hour to set that hour's funding rate. A strategy cannot trade on a rate before its hour is over.
Markets that closed still belong in the test
Testing only markets active today leaves out closed ones, which can make a strategy look better than it would have done. Some HIP-3 venues closed their markets in 2026.
Reservoir keeps those venues' folders with history up to their last trading day, so you can include them.
Reservoir adds each day the next day
Reservoir updates once a day, adding each UTC day the next day once it ends. A test that needs the current day's bars has to pull them from an API instead.
Hyperliquid's candleSnapshot returns recent bars for free. Hydromancer's candleSnapshot adds 1-second current-day bars with an API key.
A backtest can't show queue position or partial fills
Even a careful backtest cannot show where your order would have sat in the queue, whether it would have filled partially, or how other traders would have reacted. Only live trading shows that.
Run your code on Hyperliquid testnet first to verify order placement and cancels, then trade small size on mainnet. Testnet prices and liquidity differ from mainnet, so it checks the code, not the strategy.
Once a strategy passes, Hydromancer's trading bots and execution tools guide covers feeding a live bot with prices, order books and its own fills.
Next steps
• Set up AWS and run your first Reservoir query with How to Query Reservoir's Hyperliquid Data.
• Look up your fee tier, staking discount and HIP-3 fees in Hyperliquid fees explained.
• See how each hour's rate is set in Hyperliquid funding rates.
• See what a market order costs by size in Hyperliquid slippage.
Test and Validation
Code blocksEach code block was run as printed on 19 November 2026, with DuckDB 2.0.0, pandas 3.1 and pyarrow. The backtest ran in the same Python session as the funding code, on the candle code's btc_1h.parquet file and the funding table.
The candle code read all 61 daily files for September and October 2026 and wrote 1,464 hourly BTC bars, from 1 September 00:00 to 31 October 23:00 UTC. It downloaded about 1.19 GB from S3 and took 86 seconds.
The first bar opened at 78,575 and closed at 78,637, with 891.6 BTC of volume. Prices came back as DECIMAL, and DuckDB printed the hours in the computer's own time zone.
Funding historyThe funding code returned 1,464 hourly rows, one for each bar. The first rows, from 1 September 2026 00:00 UTC, had a rate of 0.0000125.
SlippageThe slippageHistory code printed 0.06 0.17: a median of 0.06 bps and a 90th percentile of 0.17 bps for $10,000 BTC buys, over the 2,000 samples from 1 September 2026. That's well under the 2 bps per side the backtest uses as a placeholder.
On these files, the example printed in-sample: 8 trades, gross 1.49%, costs 0.52%, funding 0.31%, net 0.66% and out-of-sample: 10 trades, gross -8.16%, costs 0.65%, funding 0.26%, net -9.07%.
Those lines show that the code runs and charges each cost. They aren't a result to trade on.
Each funding rate was charged to the position held during the hour that rate closed, so the rate stamped 14:00 paid for 13:00 to 14:00.
FAQ
Can I backtest on Hyperliquid for free?
Yes. Reservoir's candles and fills are free apart from AWS requester-pays charges, and Hyperliquid's own API returns funding history and recent candles at no cost.
Hydromancer's paid API mainly adds ready-made slippage history, plus current-day candles under 1 minute, which Reservoir adds only the next day.
How far back does Hyperliquid historical data go for backtesting?
Reservoir's S3 archive holds 1-second candles and every perp fill from late July 2025 onward, updated once each UTC day finishes.
Hyperliquid's native candleSnapshot returns only the latest 5,000 candles per interval, covering about 7 months of hourly bars or 3.5 days of 1-minute bars.
Should I include funding in a Hyperliquid backtest?
Yes, for any strategy that holds perps across funding times. Funding is paid every hour, so it adds up.
When the premium is zero, the rate equals the interest component of 0.00125% an hour, so a long pays about 0.03% a day. Positive rates cost longs, and negative rates cost shorts.
What fee should I use in a Hyperliquid backtest?
Use the fee for your real 14-day volume tier, or tier 0 if you're unsure: 0.045% taker and 0.015% maker on perps. Assume taker fees unless your strategy truly rests orders.
Why does my backtest look better than live trading?
Usually it's look-ahead bias, missing costs or overfitting. Act on the next bar, charge fees, funding and slippage, and judge only the out-of-sample result.
Sources
1. Hyperliquid docs: info endpoint
2. Hyperliquid docs: perpetuals info endpoint
3. Hyperliquid docs: funding
4. Hyperliquid docs: fees
5. Hyperliquid docs: about Hyperliquid
6. Hydromancer docs: Reservoir
7. Hydromancer docs: Reservoir order book schema
8. Hydromancer docs: candleSnapshot
9. Hydromancer docs: fundingHistory
10. Hydromancer docs: slippageHistory
11. Hydromancer docs: get API keys
12. How to Query Reservoir's Hyperliquid Data
Read next

Hyperliquid Frontend: Top Launch Checklist for Builders
Launch checklist for a Hyperliquid trading frontend: builder code fees, API wallet security, HIP-3 and HIP-4 markets, referrals, analytics and monitoring.

Hyperliquid Smart Money: How to Read Wallet Labels
Tell Hyperliquid market makers, delta-neutral wallets, vaults, whales and new wallets apart, and see why a wallet's label matters more than its size.

Deploy a HIP-3 Market on Hyperliquid: Guide for Builders
Step-by-step HIP-3 deployment on Hyperliquid: the 500k HYPE stake, the Dutch auction, registerAsset2, setOracle, margin tables, OI caps and fees.