Executing TWAP and VWAP on Hyperliquid via API
When an order is large enough, crossing the spread with a single market order can create meaningful market impact. Your own buy order can push the price higher, leaving you with an average entry price that is much worse than expected. To reduce this problem, professional trading desks use execution algorithms. Two of the most common are TWAP, or time-weighted average price, and VWAP, or volume-weighted average price. Source: Hyperliquid docs.
Hyperliquid’s open API makes it possible for individual developers to implement these execution styles in the on-chain perpetuals market. This guide explains how TWAP and VWAP work, how they can be implemented with Hyperliquid’s API, and when each approach makes sense. If you do not want to write and maintain execution code, OneKey Perps offers a practical way to trade on-chain perpetuals through a cleaner interface without building your own algo stack.
What Is TWAP?
TWAP is based on a simple idea: split a large order evenly over time. Instead of sending the full order at once, the algorithm submits smaller child orders at fixed intervals. The final average fill price should roughly track the time-weighted average price over the execution window.
For example, suppose you want to buy $1 million worth of BTC perpetuals over one hour. A TWAP strategy could split the order into 60 smaller orders, sending about $16,700 every minute. This avoids concentrating the entire order at one point in the order book and helps reduce the price impact of a single large trade.
TWAP is popular because it is easy to understand and does not require real-time volume modeling. Its main weakness is that it does not care whether the market is active or quiet. It will keep sending orders even during thin liquidity periods, which can increase slippage.
What Is VWAP?
VWAP goes one step further. Instead of splitting orders only by time, it also considers market volume. A VWAP execution strategy estimates how trading volume is distributed across the execution window, then sends more size during high-volume periods and less size during low-volume periods.
The goal is to achieve an average fill price close to the market’s volume-weighted average price.
VWAP usually requires real-time trade data, historical volume analysis, or both. It is more complex than TWAP, but it can be more efficient in markets where liquidity is uneven across time.
Why TWAP and VWAP Matter On-Chain
On-chain perpetuals markets can have very different liquidity profiles across different hours of the day. Depth, spreads, and order book behavior can change quickly, especially around macro events, funding resets, liquidations, or large market moves.
Hyperliquid uses an order book model that feels closer to a centralized exchange than many AMM-based derivatives venues. That makes traditional execution techniques such as TWAP and VWAP more transferable. Before deploying any execution strategy, it is worth reviewing Hyperliquid’s official documentation for order placement, order book data, fee structure, and WebSocket subscriptions.
TWAP vs. VWAP
For most individual developers, TWAP is the better starting point. VWAP can be useful once you have enough trade data to understand how volume behaves on the assets you trade.
Implementing TWAP with the Hyperliquid REST API
Basic Idea
A TWAP script can repeatedly submit child orders through Hyperliquid’s order endpoint, then wait for a fixed interval before sending the next order.
import time
import math
def execute_twap(exchange, info, coin, total_size, is_buy, duration_seconds, num_slices):
"""
Split total_size into num_slices equal child orders
and execute them over duration_seconds.
"""
slice_size = total_size / num_slices
interval = duration_seconds / num_slices
for i in range(num_slices):
# Get current market context / mark price if needed
ctx = info.meta_and_asset_ctxs()
mark_px = get_mark_price(ctx, coin)
# Market order with slippage tolerance.
# You can replace this with a limit order near the top of book.
result = exchange.market_open(
coin=coin,
is_buy=is_buy,
sz=round(slice_size, 4),
slippage=0.005 # 0.5% slippage tolerance
)
print(f"[{i + 1}/{num_slices}] Fill result: {result}")
if i < num_slices - 1:
time.sleep(interval)
print("TWAP execution complete")
This is only a simplified example. A production script should add at least:
- retry logic for failed requests;
- handling for partial fills;
- order status reconciliation;
- max slippage and max price deviation checks;
- pause or stop conditions during extreme volatility;
- logging for every submitted order, fill, cancellation, and error.
Improving Cost with Limit Orders
Using market orders is simple, but it can be expensive if spreads widen or liquidity is thin. A more careful version can post limit orders near the best bid or ask. This may reduce fees and slippage, but it introduces non-fill risk.
A common pattern is: place a limit order, wait for a short timeout, then cancel and replace or cross the spread if the order is still open.
def place_with_timeout(exchange, coin, is_buy, sz, limit_px, timeout_seconds=30):
result = exchange.order(
coin=coin,
is_buy=is_buy,
sz=sz,
limit_px=limit_px,
order_type={"limit": {"tif": "Gtc"}}
)
oid = result["response"]["data"]["statuses"][0]["resting"]["oid"]
time.sleep(timeout_seconds)
# Check whether the order is still open
open_orders = get_open_orders(coin)
if any(o["oid"] == oid for o in open_orders):
exchange.cancel(coin=coin, oid=oid)
# Use the remaining size if only partially filled
remaining_size = get_remaining_size(oid)
if remaining_size > 0:
exchange.market_open(
coin=coin,
is_buy=is_buy,
sz=remaining_size,
slippage=0.01
)
This structure gives you more control than a pure market-order TWAP, but it also requires accurate state tracking. Never assume an order is fully open or fully filled without checking the exchange state.
Calculating Real-Time VWAP with WebSocket Trade Data
VWAP requires accumulating traded volume and price multiplied by volume:
class VWAPTracker:
def __init__(self):
self.cumulative_pv = 0.0 # cumulative price * volume
self.cumulative_v = 0.0 # cumulative volume
def on_trade(self, price, size):
self.cumulative_pv += price * size
self.cumulative_v += size
@property
def vwap(self):
if self.cumulative_v == 0:
return None
return self.cumulative_pv / self.cumulative_v
With a WebSocket subscription to Hyperliquid trade data, every new trade can trigger on_trade, updating the live VWAP estimate. A VWAP execution strategy can then compare current market prices against this value and decide whether to send the next child order, delay execution, or adjust size.
In practice, a VWAP strategy also needs a volume schedule. For example, if historical data shows that 30% of daily volume usually trades during a specific window, the algorithm may allocate a larger portion of the parent order to that window. If actual volume deviates from expectations, the strategy should adjust rather than blindly follow the original schedule.
Parameter Suggestions
The right parameters depend on the asset, order size, market conditions, and your tolerance for execution risk. As a starting framework:
A conservative approach is to test with small size first, record execution results, and compare actual fills against TWAP or VWAP benchmarks before increasing order size.
Comparison with Other DEX Execution Models
Other derivatives venues can support similar ideas, but the details differ:
- dYdX also supports API-based order placement, so a similar TWAP loop can be implemented.
- GMX uses an oracle-based execution design, so execution logic differs from a central-limit-order-book model.
- Hyperliquid’s order book model is closer to centralized exchange microstructure, making TWAP and VWAP concepts relatively straightforward to adapt.
The key point is that execution algorithms are not one-size-fits-all. The venue’s matching model, fee structure, latency, liquidity, and order types all affect the final result.
Do Not Want to Write Code? Try OneKey Perps
Not every trader needs to build an execution bot. For many users, especially those trading moderate size, a safer and simpler workflow is to use a reliable interface, set limit orders carefully, and split trades manually.
OneKey Perps provides a straightforward entry point for trading on-chain perpetuals, including access to Hyperliquid, while pairing the trading experience with OneKey hardware wallet signing. This gives users a practical way to trade perps without writing API scripts or maintaining execution infrastructure.
If you want a simpler workflow, download OneKey, connect your wallet, and try OneKey Perps. For larger orders, consider splitting entries and exits, using limit orders when appropriate, and checking liquidity before execution.
FAQ
Q1: Is TWAP or VWAP better for Hyperliquid?
For most individual developers, TWAP is easier to implement and more reliable as a first execution algorithm. VWAP can work well when volume patterns are reasonably stable, but it requires more data, more modeling, and more testing. A practical path is to start with TWAP, collect execution data, then experiment with VWAP once you understand the market behavior of the assets you trade.
Q2: Can execution algorithms remove market impact completely?
No. TWAP and VWAP can reduce market impact, but they cannot eliminate it. The lower bound of execution cost depends on the size of your order relative to available liquidity. The algorithm spreads impact across time and liquidity conditions; it does not make liquidity unlimited.
Q3: How do I evaluate execution quality?
A common method is to compare your actual average fill price against a benchmark such as the TWAP or VWAP over the execution period. This is often discussed in terms of implementation shortfall. You should record every child order, including timestamp, size, price, order type, fees, and whether it was a maker or taker fill.
Q4: Can a OneKey hardware wallet be integrated with an execution script?
Yes. OneKey supports standard Ethereum-style signing interfaces. An execution script can send signing requests to a local signing flow, then submit signed transactions or messages to Hyperliquid after approval. For lower-frequency strategies such as TWAP, hardware wallet signing latency is usually not the main constraint, but the exact workflow should be tested carefully before using meaningful size.
Q5: What should I do if the market moves sharply during execution?
Use price protection rules. For example, if the market price moves more than a preset threshold, such as 2%, from the execution start price, the script can pause or stop. This helps avoid continuing to build a position during a fast adverse move. The threshold should be set based on the asset’s volatility, your order size, and your risk limits.
Conclusion
TWAP and VWAP are practical tools for reducing the execution cost of large orders. Hyperliquid’s open API makes these strategies possible in on-chain perpetuals markets, whether you implement them with code or approximate the logic manually by splitting orders over time.
The core idea is the same: avoid sending one oversized order, reduce immediate market impact, and manage execution risk with clear rules. If you want a simpler way to trade on-chain perps without building your own execution system, OneKey Perps is a practical place to start.
Risk warning: Algorithmic execution cannot guarantee a specific fill price. Market volatility, insufficient liquidity, API issues, failed orders, or technical errors can cause actual execution costs to differ significantly from expectations. Perpetual futures trading is high risk and may result in partial or total loss of funds. This article is for technical reference only and is not financial, legal, or investment advice. Trade carefully and only after understanding the risks.



