سياسة

Building Perpetual Funding Rate Prediction Models: Machine Learning Approaches for Forecasting Carry Returns on Hyperliquid

Funding rates in perpetual futures markets represent a direct and recurring income stream available to traders who hold positions against the prevailing market direction. On Hyperliquid, which processes over 70% of monthly on-chain perpetual trading volume, funding rates fluctuate based on the imbalance between long and short open interest, creating predictable patterns that systematic traders can exploit. Unlike centralized exchanges where funding rate history is opaque or proprietary, Hyperliquid’s fully on-chain central limit order book (CLOB) makes all order data and funding rate mechanics directly observable, enabling data scientists to build, backtest, and deploy prediction models with real-time market signals.

The practical challenge for a quantitative trader or algorithmic fund is converting that transparency into actionable forecasts. Funding rates change multiple times per hour, yet their future values depend on order book dynamics, liquidation cascades, leverage changes, and sentiment shifts that conventional time-series models often miss. This tutorial walks through sourcing historical funding rate data, engineering meaningful features from on-chain order book snapshots, training machine learning models with realistic performance expectations, and understanding why a model that works during calm markets may fail during a liquidation cascade. The goal is not to promise consistent alpha, but to provide a repeatable workflow for hypothesis testing and model validation that separates signal from noise.

On-chain order book interface showing real-time funding rates, open interest levels, and order depth across multiple perpetual contracts on Hyperliquid

Sourcing and structuring Hyperliquid funding rate data

Hyperliquid publishes funding rates and order book state through its HTTP API and WebSocket streams, making historical reconstruction possible without relying on third-party data vendors. The API endpoint `/info` accepts queries for `fundingHistory` filtered by asset, timestamp range, and pagination. For initial exploration, request funding history for a liquid contract such as BTC or ETH perpetuals over a rolling 90-day window, capturing at least 10,000 to 50,000 individual funding events. Each event includes the timestamp, funding rate (expressed as a percentage per 8-hour period), and the contract’s position index, which allows you to cross-reference with open interest at that time.

The raw funding data should be structured in a time-indexed DataFrame with columns for asset, timestamp, funding rate, cumulative funding accrued, open interest (long and short separately), and mark price. Hyperliquid’s funding rate mechanism depends on the imbalance between long and short positions: when longs outnumber shorts, the funding rate becomes positive, paying shorts to rebalance the market. This directional imbalance is not always predictable from price alone, making order book state critical. Store this base dataset in a reliable format such as Parquet, with UTC timestamps and consistent decimal precision for funding rates.

A second data source you will need is order book snapshots. The WebSocket connection `/ws` delivers real-time order book updates via the `book` channel, including all live orders at each price level. For backtesting, you can reconstruct order book state from historical WebSocket logs or query the snapshot API at regular intervals (e.g., every 10 or 60 seconds). Record the midpoint price, bid-ask spread, cumulative volume at various depth levels (±0.5%, ±1%, ±2% from midpoint), and the imbalance ratio (total bid volume divided by total ask volume). These snapshots form the feature set that will drive predictions.

Important: Hyperliquid’s on-chain CLOB means every order is settled on-chain with sub-second block finality. This creates an opportunity but also a constraint. Your data collection frequency must be fast enough to capture meaningful order book changes (at least 1–5 snapshots per second during active trading), but you will also see order arrivals, cancellations, and matching that happen faster than any off-chain aggregation layer. Design your pipeline to handle latency and partial fills transparently, or backtest results will overstate real-world performance.

Engineering features from order book microstructure

Raw funding rates and order book snapshots alone do not make effective machine learning inputs. You must engineer features that capture the underlying mechanisms driving funding rate changes. The most direct feature is the long-short open interest ratio: divide cumulative long notional by total open interest. When this ratio exceeds 0.5 (more longs), funding rates tend to rise. However, the predictive power is weak on short timescales because funding rates adjust over hours, not seconds. A ratio change by 2% may not move funding rates until the next funding epoch or when enough traders notice and reposition.

Order book imbalance captures market microstructure at higher frequency. Calculate the ratio of cumulative bid volume to cumulative ask volume across multiple depth windows. You might compute separate ratios for the top 1% of the spread, the top 2–5%, and the top 5–10%. A ratio above 1.0 indicates more buy pressure, which often precedes positive funding rates when that pressure translates into position accumulation. To reduce noise, smooth these ratios using an exponential moving average (EMA) with a half-life of 30–60 seconds. Test different window sizes and depth thresholds empirically; there is no universal “correct” level.

A second class of features captures recent price and volatility dynamics. Compute the rolling hourly return, the log-return standard deviation over the past hour, and the rolling correlation between price changes and order book imbalance. Include also the derivatives trading context: the ratio of perpetual volume to spot volume (if available), the time since the last liquidation cascade (identifiable from a sudden jump in funding rates and order book volatility), and the absolute distance between mark price and index price (which can widen during stressed conditions). These features help the model understand the broader market regime rather than relying solely on order book snapshots.

Finally, construct lagged features: funding rates from the previous 1, 4, 8, and 24 hours. Funding rates exhibit some autocorrelation—a high positive rate now often precedes sustained positive rates, though reversals are sharp and unpredictable. Use a rolling window of the past 100–200 funding observations (corresponding to a few hours of history) to train a neural network or gradient boosting model. Avoid look-ahead bias by ensuring that every feature at time t uses only data available before time t. When backporting historical data, lag every feature by at least one observation interval (typically 1–5 minutes for this prediction task).

Training and cross-validation strategies for funding rate models

Funding rate prediction is a regression task: you are forecasting the funding rate at time t+1, t+2, or t+8 (corresponding to the next funding event or the rate 8 hours in the future). Begin with a simple baseline—a linear regression predicting the next funding rate from open interest ratio and order book imbalance—then compare against ensemble models such as XGBoost or LightGBM, which often outperform neural networks on tabular trading data with limited samples.

The most common mistake in training trading models is using standard cross-validation (random train-test split), which creates a look-ahead bias. Funding rates and order book state are time-series data; a model trained on data from March and tested on February has already seen the future relative to its own predictions. Instead, use walk-forward validation: divide your 90-day dataset into overlapping windows (e.g., train on days 1–30, test on days 31–35, then slide forward and retrain on days 6–35, test on days 36–40). This mimics real deployment where the model is retrained periodically and then backtested on held-out future data.

Set aside the most recent 2–4 weeks of data as an out-of-sample test set that you do not touch until after hyperparameter tuning is complete. Evaluate models using mean absolute error (MAE) and mean squared error (MSE) on the test set, but also compute the directional accuracy: the percentage of time the model correctly predicts whether the next funding rate will be higher, lower, or flat. A model with MAE of 0.001 (0.1% per 8-hour period) may sound good, but if it only predicts direction correctly 52% of the time, its practical trading edge is minimal after accounting for execution costs and slippage.

Be aware of regime shifts. Funding rates during a bull market (when leverage is high and risk appetite is elevated) behave differently from rates during a drawdown (when liquidations cascade and funding rates spike). Train separate models for different volatility regimes, or include volatility as a categorical feature in a single ensemble model. Test robustness by training on one bull-bear cycle and evaluating on a different cycle. If performance degrades significantly, the model is likely capturing regime-specific noise rather than fundamental order book mechanics.

Understanding model limitations and real-world performance gaps

A typical machine learning model trained on Hyperliquid funding rate data will achieve 51–55% directional accuracy on clean test data, and 50–52% on truly held-out out-of-sample data. This is marginally better than a coin flip. Yet it is not useless: in a market where funding rates average 0.01% per 8-hour period, predicting correctly even 2% more often than chance corresponds to an annualized edge of 3–5% before fees. However, this edge evaporates if execution costs more than 0.005% per trade or if you trade too frequently and move the order book.

Several factors explain the gap between model accuracy and trading profits. First, funding rates are mean-reverting; they exhibit strong autocorrelation in the short term, but large swings revert sharply. A model that predicts high funding rates will continue is often right for the next 1–4 hours but wrong over 24 hours. Test models at multiple prediction horizons (1 hour ahead, 4 hours, 24 hours) and do not assume that a feature set effective for one horizon transfers to another. Second, order book microstructure changes abruptly during liquidation cascades. When Hyperliquid’s on-chain CLOB processes a wave of liquidations, the order book can reverse and funding rates spike in ways that no lagged feature set captures. Your model will underpredict these events systematically.

Third, leverage and position sizing matter more than direction. Suppose your model predicts positive funding with 53% accuracy. Trading a fixed amount per prediction will generate modest returns during normal conditions, but a single adverse outlier (a flash crash or cascading liquidation) can wipe out months of gains if your position size is too large. In live trading, reduce position size proportionally to model confidence: use the predicted probability (from a logistic regression or the probability output of a gradient boosting model) to scale position size, not binary predictions. This turns a 53% directional model into a more conservative 48% performer by volume, but with much lower tail risk.

Finally, Hyperliquid’s zero gas fees for trading create an illusion of free liquidity. You can enter and exit without paying gas, but you will still incur taker fees (typically 0.02% per side) and face bid-ask spread costs (0.01–0.05% depending on liquidity and market conditions). If your model’s edge is 0.05% per round-trip trade, you are breaking even or losing money. Design backtests that include realistic fees, spread assumptions, and partial fill rates. Many published trading models fail in production not because they are wrong, but because they were backtested without transaction costs.

Building a production prediction pipeline

Once you have trained and validated a model, deploying it requires more infrastructure than offline notebooks. You need a real-time data ingestion layer that collects funding rates and order book snapshots via WebSocket, a feature engineering module that computes all lagged and derived features with minimal latency, a model serving layer that outputs predictions, and a backtesting framework that simulates position entry and exit with realistic market assumptions. The purpose-built Layer 1 blockchain for trading exposes the necessary APIs, but you must build the integration yourself.

Start with a data pipeline that logs all order book snapshots and funding rate changes to a time-series database such as InfluxDB or TimescaleDB. Write a Python module that subscribes to Hyperliquid’s WebSocket stream, buffers incoming messages, and computes features in real-time. Use a process pool to ensure that feature computation does not block incoming data collection. Store computed features in a fast key-value store (Redis) so that your model serving layer can retrieve the latest feature vector with sub-100ms latency.

For model serving, containerize your model (using Docker) and deploy it on a machine with low-latency network access to Hyperliquid’s API endpoints. Avoid cloud services with variable latency unless your model operates on hourly or longer prediction windows (in which case latency matters less). Every 10–60 seconds, pull the latest feature vector, generate a prediction, and log the prediction along with the realized funding rate 1, 4, and 8 hours later. This creates a continuous evaluation dataset that tells you whether your model is drifting. If weekly accuracy drops below your backtest baseline, retrain immediately; trading with a degraded model is worse than trading a simple baseline.

Include monitoring and alerts. Track the model’s directional accuracy on a rolling 7-day basis. If accuracy drops below 50.5%, send an alert and consider reverting to a simpler strategy or pausing trading. Monitor latency: if order book snapshots are arriving more than 5 seconds apart, your feature computation will use stale data. Set up automated retraining every 2–4 weeks using the most recent 60–90 days of data, and always backtest the retrained model on the next week of data before deploying to production.

Handling non-stationary market conditions and model drift

The funding rate prediction task is inherently non-stationary. As more traders adopt algorithmic strategies, as Hyperliquid’s market structure evolves, and as the broader crypto macro environment shifts, the relationships between order book imbalance and future funding rates will change. A model trained on 2024 data may perform poorly in 2025 if market participants have learned the same patterns and begun to arbitrage them away.

Combat drift through adaptive retraining and ensemble approaches. Rather than retraining a single model every 4 weeks, maintain a rolling ensemble of models trained on different 30-day windows. Combine their predictions using equal weighting or a confidence-based scheme (weight by recent accuracy). This approach is slower to respond to true shifts in market structure, but it is also more robust to temporary noise. Alternatively, track the ratio of your model’s edge to transaction costs: if edge declines toward cost, increase the retraining frequency or reduce position size to avoid trading unprofitable predictions.

Use adversarial validation to detect regime changes. Train a classifier to distinguish between data from the first 45 days of your dataset and data from the last 45 days. If the classifier achieves >55% accuracy, it means the statistical properties of your features have shifted significantly. That is a signal to either retrain your funding rate model or inspect which features have changed most. Perhaps order book depth has changed, or the distribution of funding rates has widened. Understanding the change is more valuable than blindly retraining.

Expect that your model’s edge will decline over time as the market becomes more efficient. If your initial backtest showed 3% annualized edge, live trading will likely show 1–2%, and six months later, 0.5–1% as competitors deploy similar approaches. This is not a flaw in your model; it is the market pricing in the opportunity. Plan for diminishing returns and design your system to be robust to lower edge. Use position sizing scaled to confidence, maintain low latency and fees, and continuously test new feature combinations that might capture edge others have not yet exploited.

Case study: Predicting BTC perpetual funding rates during volatile regimes

Consider a concrete example: training a model to predict 8-hour funding rates for BTC perpetuals during periods of high volatility (rolling 30-day realized volatility above 3% annualized). You collect 60 days of order book snapshots (1 snapshot per 30 seconds) and funding rate observations from Hyperliquid. This yields approximately 172,800 snapshots and 180 funding rate observations (funding rates update roughly 3 times per day). Features include the long-short ratio, order book imbalance at multiple depth levels, rolling volatility, and lagged funding rates from the past 1, 4, and 8 hours.

Train a LightGBM model on the first 40 days, tune hyperparameters on days 41–50 using walk-forward validation, and evaluate on days 51–60. The model achieves 54% directional accuracy on the test set and 52% on truly held-out data from a different volatile period (e.g., a separate market crash). Applying a 0.02% taker fee and 0.02% spread cost, each correct prediction yields roughly 0.005% profit (50 bps of funding earned minus half the round-trip cost), and each incorrect prediction costs 0.005%. With 52% accuracy, expected profit per trade is 0.000%, or breakeven. This is not a viable trading strategy.

However, if you scale position size by model confidence (the probability output from LightGBM’s sigmoid transformation), the effective directional accuracy drops to 50.5% on high-confidence predictions, but you avoid trading on uncertain signals altogether. Over 100 high-confidence predictions, you earn 0.05% total return minus fees, or roughly 0.01–0.02% net. This is modest, but if compounded over months and combined with other uncorrelated strategies, it contributes to a diversified portfolio edge. The key is understanding that marginal improvements in accuracy or cost reduction matter greatly when baseline edge is low.

Tools and resources for implementation

Build your pipeline using Python, focusing on libraries with strong support for time-series data and efficient computation. Use `pandas` and `polars` for data manipulation, `scikit-learn` for preprocessing and cross-validation, `xgboost` and `lightgbm` for model training, and `hyperliquid-python-sdk` (the official Hyperliquid SDK) for data access. For WebSocket management and async I/O, use `websockets` or `asyncio`, ensuring your data collection does not block. Store features and predictions in `parquet` format using `pyarrow`, which compresses well and supports efficient time-range queries.

For backtesting, consider frameworks such as `backtrader` or `freqtrade`, though you may need to build custom extensions for Hyperliquid’s specific order book API. Alternatively, write a minimal simulation in pure Python: loop through your out-of-sample data, pull the latest feature vector at each timestamp, generate a prediction, and simulate position entry and exit with realistic bid-ask spread and slippage. Log every prediction and result to a database, then compute metrics (Sharpe ratio, maximum drawdown, directional accuracy, profit factor) offline.

Monitor and log everything. Every prediction, every trade, every realized outcome should be recorded with full traceability. Use structured logging (JSON format) to capture prediction value, model version, market conditions, fees paid, and slippage incurred. This creates a continuous feedback loop: if you notice a pattern in which your model fails (e.g., consistently wrong during the first hour after liquidations), you can design features to capture that pattern and retrain. Data science for trading is not a one-time project; it is continuous iteration and refinement.

Frequently asked questions

How much historical data do I need to train a reliable funding rate prediction model?

Start with at least 60–90 days of order book snapshots and funding rate observations. This captures multiple market regimes and provides enough samples (typically 10,000 to 50,000 observations after feature engineering) for a robust model. Avoid training on less than 30 days unless your prediction horizon is very short (1–4 hours), as shorter datasets may not contain enough variation in market conditions. Always hold out the most recent 2–4 weeks for evaluation.

What is the realistic edge I should expect from a funding rate prediction model?

Most published models achieve 51–55% directional accuracy, which translates to 0.01–0.05% expected profit per round-trip trade after accounting for fees and slippage. This is a marginal edge; it requires low-cost execution, high-confidence predictions (scaled position sizing), and robust risk management to be profitable. Do not expect 1–2% monthly returns from a funding rate model alone. If your backtest shows 10%+ monthly returns, recheck for look-ahead bias or unrealistic cost assumptions.

How often should I retrain my funding rate prediction model?

Retrain every 2–4 weeks using the most recent 60–90 days of data. More frequent retraining (weekly) may reduce overfitting to temporary patterns, but less frequent retraining (monthly or longer) leaves you exposed to market regime shifts. Monitor directional accuracy on a rolling 7-day basis; if it drops below 50.5%, retrain immediately or reduce position size. Use adversarial validation to detect regime changes and trigger emergency retraining if market structure shifts significantly.

إغلاق