Technical documentation · last updated 26 November 2026
Ballast
Ballast changes the leverage of an open Hyperliquid perpetual position by adding or removing isolated margin. The position is not closed and no order is placed. This document describes the mechanism, derives the formulas, and records what has been verified and how.
1. Overview
A trader normally fixes leverage when a position opens. After that, changing it means closing and reopening, which costs two taker fees and gives up the entry. Ballast treats leverage as a quantity to manage for as long as the position is open.
- Non-custodial. Funds stay in the user's own Hyperliquid account. Ballast holds a trading agent key that Hyperliquid does not allow to withdraw.
- Two modes. Agentic: a model decides up or down every 6 seconds. Manual: the user sets the leverage.
- Bounded. Each position has a margin budget. The agent cannot commit more than it.
- Range. 1x to 10x, which is the widest range that margin changes alone can reach on Hyperliquid.
2. Architecture
| Component | Role |
|---|---|
| Risk engine | Volatility forecast, shock detection, target leverage. Deterministic code. |
| Decider | Jev, TypeSafe's decision model. Returns the probability that leverage should be reduced. The risk engine is the fallback. |
| Broker | Signs and sends Hyperliquid actions for one account using the official Python SDK. |
| Session | Per-browser state: connection, position metadata, mode, budget, decision log. |
| Market data | Prices, one-minute candles and asset metadata from Hyperliquid's public API. Shared by all sessions. |
| Deposit path | Circle CCTP, Arbitrum to HyperCore. Built server-side, signed and sent by the user's wallet. |
3. Mechanism
For a position of size s at mark price P:
N = s × P notional E = margin + unrealised PnL equity in the isolated position L = N / E effective leverage side = +1 long, −1 short
Leverage is a ratio, so it can change through N (trading size) or through E (moving margin). Ballast changes E. On Hyperliquid this is the updateIsolatedMargin action, which is not a trade: no taker fee, no slippage, no change to size or entry.
Hyperliquid enforces one constraint on removals. After margin is removed, the margin remaining must satisfy:
E ≥ max( N / leverage_setting , 0.10 × N )
Ballast opens positions with the exchange leverage setting at 10x, so the binding term is 0.10 × N and effective leverage can be moved anywhere in [1x, 10x].
4. Derivations
4.1 Liquidation price
Hyperliquid liquidates an isolated position when equity falls below maintenance margin, with maintenance rate m = 1 / (2 × max leverage of the asset).
Condition at liquidation price P_liq:
E + side · s · (P_liq − P) = m · s · P_liq
Solve for P_liq:
E − side·s·P = P_liq · s · (m − side)
P_liq = (side·s·P − E) / ( s · (side − m) )
Since side² = 1, multiply through by side:
P_liq = P − side · (E − m·s·P) / s / (1 − m·side)
This is the formula in Hyperliquid's documentation, with margin_available = E − m·N.
4.2 Distance to liquidation depends only on leverage
d = side · (P − P_liq) / P = (E − m·N) / ( N · (1 − m·side) ) = (1/L − m) / (1 − m·side) using E = N / L
Size and price cancel. For a HYPE long (m = 5%): 2x gives 47.4%, 5x gives 15.8%, 10x gives 5.3%.
4.3 Target leverage
Invert 4.2. To place liquidation a distance d* away:
L* = 1 / ( d* · (1 − m·side) + m )
The required distance is set from forecast volatility:
d* = k × mult × σ_H k = 3, H = 60 minutes L* is then clamped to [1, 10]
4.4 Volatility forecast
r_t = ln(P_t / P_{t−1}) one-minute log return
v ← v + α·(r_t² − v), α = 1 − 0.5^(1/h) EWMA variance, half-life h
σ = √ max(v_fast, v_slow) h_fast = 8, h_slow = 96 minutes
σ_H = σ · √H
Shock: z = max(|r_t|, range_t / 1.67) / σ_{t−1}
mult = 1.5 for 16 minutes after any z > 4, else 1
Taking the larger of the fast and slow variance makes the forecast rise quickly and fall slowly.
4.5 The margin move
ΔM = N / L_new − E ΔM > 0 adds margin, ΔM < 0 removes it
After the move, equity is E + ΔM = N / L_new, so leverage is exactly L_new.
4.6 Loss is bounded by the budget
Claim. The loss on a Ballast-managed position cannot exceed its margin budget B.
Proof. Let C be the net margin committed to the position: opening collateral, plus every amount added, minus every amount removed.
- At open,
C = collateral ≤ B, since the budget is set to at least the collateral. - An add of
ΔM > 0is sent only ifC + ΔM ≤ B. A removal lowersC. SoC ≤ Bholds after every action, by induction. - An isolated position can lose at most the margin posted to it. Liquidation closes the position; it cannot draw on the rest of the account.
- Therefore realised loss ≤
C≤B. ∎
The bound relies on Hyperliquid's isolated-margin rule in step 3, and excludes funding payments, which are settled against the position's margin.
5. Decision loop
Every 6 seconds, for each session with an open isolated position in Agentic mode:
1. Read the position from Hyperliquid: N, E. L = N / E
2. Compute σ_H, mult and the target L* (section 4)
3. Describe the position in words (see table)
4. Ask the decider: should leverage be reduced now?
p ≥ 0.5 → DOWN p < 0.5 → UP
5. L_new = round(L) ± 1
6. Settle rule: if |L − L*| < 0.6 and the move goes away from L*, hold
7. Limits: 1 ≤ L_new ≤ 10, budget, free balance
8. Send ΔM = N / L_new − E as one updateIsolatedMargin action
9. Re-read the position. If leverage moved the wrong way, pause the agent
Jev is weak with numeric precision by TypeSafe's own documentation, so the numbers are converted to categories before the call:
| Input | Categories |
|---|---|
Liquidation distance in hourly moves, d / σ_H | very close (<2), close (2–3), comfortable (3–5), far away (>5) |
| Volatility now against one hour ago | falling (<0.8), steady, rising (>1.25) |
| Shock multiplier above 1 | recent price shock: yes, no |
| Five-minute price change, signed by side | hard against, drifting against, flat, drifting in favour, strongly in favour |
| PnL as a share of margin | large loss, small loss, about flat, small profit, large profit |
| Leverage minus target | below, at, above the safe level |
The decider chooses a direction. Steps 6 to 9 are code and apply regardless of its answer. If the model call fails or times out (4 seconds), the risk engine decides: UP if L < L*, otherwise DOWN.
6. Connection and signing
Hyperliquid lets an account approve an agent: a second key that can place orders and move margin for the account but cannot withdraw or transfer. Ballast uses one agent per session.
- The server generates a fresh key pair for the session.
- The user's wallet signs an EIP-712
ApproveAgentmessage naming the agent's address. - The server recovers the signer, checks it equals the claimed address, and submits the approval to Hyperliquid.
- From then on the agent signs that user's orders and margin changes.
domain { name: "HyperliquidSignTransaction", version: "1",
chainId: <wallet chain>, verifyingContract: 0x0 }
primaryType HyperliquidTransaction:ApproveAgent
message { hyperliquidChain: "Mainnet", agentAddress, agentName: "ballast", nonce }
The agent key is held in server memory and in the user's browser storage, so the browser can reconnect after a server restart. On reconnect the server asks Hyperliquid whether that key is still an approved agent of that account before using it. Disconnecting discards the key on both sides.
7. Order lifecycle
| Step | Hyperliquid action | Notes |
|---|---|---|
| Open | updateLeverage (isolated, 10x)order (IOC at 1% through the mid)updateIsolatedMargin (+) | The position opens at 10x, then margin is added to reach the chosen leverage. Size is rounded to the asset's size decimals. Minimum $10. |
| Adjust | updateIsolatedMargin (±) | One action per call. Amounts are rounded to cents. |
| Close | order (reduce-only IOC) | Whole position. Remaining margin returns to the account. |
Positions the session did not open are displayed and start in Manual mode. The agent does not touch them until the user switches it on.
8. Account modes
Hyperliquid accounts report balances differently depending on their mode, read with the userAbstraction info request.
| Mode | Trading balance used by Ballast |
|---|---|
Standard (default, disabled) | withdrawable from the perps clearinghouse state. Spot USDC is separate and can be moved across. |
Unified (unifiedAccount, portfolioMargin) | Spot USDC total − hold. Hyperliquid's documentation states that perps state is "not meaningful" in these modes. Spot-to-perps transfers are disabled by the exchange. |
9. Deposits and withdrawals
Deposit: Arbitrum USDC to the trading balance
Deposits use Circle's Cross-Chain Transfer Protocol, following Circle's Arbitrum-to-HyperCore guide. The user's wallet makes one signature and one transaction.
- Sign an EIP-3009
ReceiveWithAuthorizationon USDC, authorising the CctpExtension contract to pull the amount. - Send
CctpExtension.batchDepositForBurnWithAuth(auth, burn)on Arbitrum. - Circle mints on HyperEVM and its CctpForwarder credits the recipient on HyperCore.
| Contract | Chain | Address |
|---|---|---|
| USDC (native) | Arbitrum One | 0xaf88d065e77c8cC2239327C5EDb3A432268e5831 |
| CctpExtension | Arbitrum One | 0xA95d9c1F655341597C94393fDdc30cf3c08E4fcE |
| CctpForwarder | HyperEVM | 0xb21D281DEdb17AE5B501F6AA8256fe38C4e45757 |
burn = ( amount, destinationDomain = 19, mintRecipient = CctpForwarder,
destinationCaller = CctpForwarder, maxFee = 200000,
minFinalityThreshold = 1000, hookData )
hookData (56 bytes) = "cctp-forward" padded to 24 | version 0 (4) | length 24 (4)
| recipient address (20) | destination dex 0 = perps (4)
Circle warns that if mintRecipient or destinationCaller is not the CctpForwarder, the funds are unrecoverable. Both are constants in the code and are never taken from user input. The forwarding fee is a flat 0.20 USDC. Ballast enforces a 5 USDC minimum.
Withdrawal
A withdraw3 action, signed by the owner's wallet. The agent cannot produce it. Hyperliquid sends USDC to the wallet on Arbitrum.
10. Verification
Each item states what was checked and how. Items marked verified were observed directly. Section 10.8 lists what has not been verified.
10.1 Arithmetic verified
Ten unit tests, all passing.
| Test | What it establishes |
|---|---|
| Liquidation price | At the computed price, equity equals maintenance margin to nine decimal places, for longs and shorts. |
| Distance round trip | lev_for_distance(liq_distance(L)) = L for several leverages and both sides. |
| Distance against price | Section 4.2 agrees with section 4.1 for a 20x long. |
| Budget on add | Rising volatility adds margin and total commitment stays within the budget. |
| Removal floor | A removal never leaves less than 10% of notional. |
| Bounded loss | Across a falling, oscillating path the simulated loss never exceeds the budget. |
10.2 Signing verified
For agent approval, withdrawal and spot-to-perps transfer, the message Ballast builds for the wallet was signed with a throwaway key and compared with the signature produced by Hyperliquid's official SDK for the same action. The signatures were byte-identical in all three cases. A signature from a different wallet is rejected before anything is sent.
10.3 Deposit path verified
Sixteen read-only checks against live Arbitrum and HyperEVM, all passing. The most important:
- USDC's on-chain
DOMAIN_SEPARATORequals the EIP-712 domain Ballast signs against. - The function selector
0x95878db1is present in the deployed CctpExtension bytecode. - Both forwarder fields in the encoded call decode back to the CctpForwarder address.
- A simulated deposit from an unfunded throwaway key reverts with "transfer amount exceeds balance", which means the signature and encoding were accepted up to the token transfer.
- The same simulation with a balance override completes successfully.
Live result. A 10 USDC deposit made through the terminal was credited as 9.80 USDC:
| Time (UTC) | Event | From | Amount |
|---|---|---|---|
| 2026-11-26 19:31:51 | USDC credited to account 0x81f0…60f7 | Circle CoreDepositWallet 0x6b9e…0a24 | 9.80 USDC |
The difference is the 0.20 USDC forwarding fee.
10.4 Live orders verified
Two positions opened and closed through the terminal on mainnet, read back from Hyperliquid's public fill history.
| Time (UTC) | Action | Size | Price | Notional | Fee |
|---|---|---|---|---|---|
| 19:38:58 | Open long HYPE | 0.72 | $62.096 | $44.71 | $0.020119 |
| 19:39:21 | Close long HYPE | 0.72 | $62.080 | $44.70 | $0.020113 |
| 19:52:46 | Open long HYPE | 0.73 | $62.060 | $45.30 | $0.020386 |
| 19:53:27 | Close long HYPE | 0.73 | $62.081 | $45.32 | $0.020393 |
Every fee equals 0.045% of notional, Hyperliquid's base taker rate, which confirms the orders executed as ordinary taker fills. Realised PnL was −$0.0115 and +$0.0153. The account is a unified account, so these also confirm that opening and closing work in that mode.
10.5 Decider verified
Jev was called on the live API with five described positions. Latency was 100 to 170 ms per call.
| Position described | P(reduce) | Call |
|---|---|---|
| Far from liquidation, volatility falling, in profit | 6% | UP |
| Far from liquidation, volatility steady, flat | 7% | UP |
| Comfortable distance, at the target leverage | 8% | UP |
| Close to liquidation, drifting against, small loss | 97% | DOWN |
| Very close, volatility rising, large loss | 98% | DOWN |
A mixed case (far from liquidation but drifting against, with a small loss) returned 60%. Five cases show the model separates clear situations. They are not a calibration study.
10.6 Session isolation verified
A test starts the server in hosted mode and drives it as two browsers. Thirteen checks pass, including: separate session cookies, a different agent issued to each user, one user's market or mode change not affecting the other, one user unable to complete the other's wallet connection or deposit, the operator's local wallet settings ignored when hosted, and cross-site requests refused.
10.7 Backtest verified
Fifty-two days of 15-minute Hyperliquid candles. For each coin, 1,076 positions of $10,000 notional opened at 20x with a $1,500 budget and held 24 hours, on every start bar and both sides so that entries carry no edge. The same entries were managed four ways.
| Coin | Policy | Liquidated | Avg $ in position | Exposure kept | Mean PnL |
|---|---|---|---|---|---|
| BTC | Static 20x | 13.5% | $484 | 94% | −$19 |
| Cross, full budget | 0.0% | $1,494 | 100% | −$13 | |
| Close and reopen | 0.0% | $473 | 88% | −$15 | |
| Dynamic margin | 0.1% | $654 | 99% | −$17 | |
| ETH | Static 20x | 30.0% | $461 | 84% | −$21 |
| Cross, full budget | 0.0% | $1,494 | 100% | −$13 | |
| Close and reopen | 0.0% | $459 | 79% | −$12 | |
| Dynamic margin | 2.9% | $733 | 96% | −$18 | |
| SOL | Static 20x | 42.3% | $425 | 75% | −$27 |
| Cross, full budget | 0.0% | $1,494 | 100% | −$13 | |
| Close and reopen | 0.0% | $444 | 74% | −$17 | |
| Dynamic margin | 2.4% | $809 | 96% | −$22 |
Reading it. Dynamic margin kept 96 to 99% of exposure with a liquidation rate near that of cross margin, while holding roughly half the capital in the position. It did not improve mean PnL: with no-edge entries every policy loses about its fees, and dynamic margin was slightly worse than cross. The result supports a claim about capital efficiency and survival, not about returns.
Caveats. This is a bar-level simulation. It used an earlier engine configuration (20x opens, 15-minute bars) than the live terminal (10x cap, one-minute bars). Positions overlap, funding is ignored, and 52 days is a short sample.
10.8 Not yet verified
- A live agent-driven margin change. The two live positions were open for 23 and 41 seconds, and no margin change was recorded on either. The central action,
updateIsolatedMarginon a real position, has been exercised in simulation and its payload path is the SDK's own, but it has not been observed on mainnet. - Direction of a removal. The SDK example confirms a positive amount adds margin. That a negative amount removes it is assumed. The wrong-way check in the decision loop exists to catch an error here.
- Isolated margin on unified accounts. Hyperliquid's documentation does not state whether isolated margin changes behave identically in unified mode.
- Withdrawal. The payload matches the SDK. No live withdrawal has been made.
- Load. Tested with two concurrent sessions, not with many.
10.9 Reproducing the checks
python -m unittest tests.test_ballast # 10.1 arithmetic python tests/check_deposit.py # 10.3 deposit path, read-only python tests/check_multiuser.py # 10.6 session isolation python -m ballast backtest --coin BTC # 10.7 backtest
Live records in 10.3 and 10.4 can be read from Hyperliquid's public API with the userFills and userNonFundingLedgerUpdates info requests for the account.
11. Security model
| Property | How it is enforced |
|---|---|
| Ballast cannot withdraw user funds | Hyperliquid does not permit agents to withdraw or transfer. Withdrawals need the owner's wallet signature. |
| One user cannot act for another | Per-session agent keys. The approval signature must recover to the claimed address. |
| Other websites cannot send commands | State-changing requests are rejected unless their origin is this site. The session cookie is HttpOnly, Secure and SameSite=Lax. |
| The operator's own wallet is not exposed | Local wallet settings are ignored whenever the server is not bound to localhost. |
| The agent's spending is capped | Margin budget per position and a per-user position size cap, both checked in code before any action. |
| A wrong margin direction is contained | The position is re-read after every change. If leverage moved against the intended direction, the agent pauses. |
| Deposit funds cannot be misrouted | Forwarder addresses are constants. The recipient is the connected account. |
What the agent key does allow: placing orders and moving margin on the account. A compromised agent key could therefore trade the account badly, though it could not withdraw from it. The key is trade-only, is replaced on each new connection, and is discarded on disconnect.
12. Limits and risks
- Liquidation is still possible. A price gap can pass the liquidation price between two calls. The budget can be exhausted. The 3-sigma distance is a tuning choice, and crypto returns have fatter tails than the normal model behind it.
- No view on direction. The engine manages survival. It does not predict price and does not improve expected returns.
- Funding is displayed but is not part of the target.
- Server restarts. Sessions are held in memory. After a restart the browser reconnects automatically when it is next opened; until then an open position is unmanaged.
- Single instance. The server must run as one instance. Hyperliquid's per-IP rate limits bound the number of concurrently managed accounts.
- Markets. HYPE, BTC, ETH and SOL perpetuals. One managed position per user at a time.
Leveraged trading can lose the entire margin posted to a position. Nothing in this document is financial advice.