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.

2. Architecture

BrowserTerminal UI. Holds the wallet. Signs the agent approval, deposits and withdrawals.
HTTPS, session cookie
Ballast serverOne session per user. Holds that user's agent key in memory, runs the risk engine and the decision loop.
signed actions
HyperliquidOrder book, margin and liquidation. The source of truth for every balance and position.
ComponentRole
Risk engineVolatility forecast, shock detection, target leverage. Deterministic code.
DeciderJev, TypeSafe's decision model. Returns the probability that leverage should be reduced. The risk engine is the fallback.
BrokerSigns and sends Hyperliquid actions for one account using the official Python SDK.
SessionPer-browser state: connection, position metadata, mode, budget, decision log.
Market dataPrices, one-minute candles and asset metadata from Hyperliquid's public API. Shared by all sessions.
Deposit pathCircle 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.

  1. At open, C = collateral ≤ B, since the budget is set to at least the collateral.
  2. An add of ΔM > 0 is sent only if C + ΔM ≤ B. A removal lowers C. So C ≤ B holds after every action, by induction.
  3. 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.
  4. 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:

InputCategories
Liquidation distance in hourly moves, d / σ_Hvery close (<2), close (2–3), comfortable (3–5), far away (>5)
Volatility now against one hour agofalling (<0.8), steady, rising (>1.25)
Shock multiplier above 1recent price shock: yes, no
Five-minute price change, signed by sidehard against, drifting against, flat, drifting in favour, strongly in favour
PnL as a share of marginlarge loss, small loss, about flat, small profit, large profit
Leverage minus targetbelow, 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.

  1. The server generates a fresh key pair for the session.
  2. The user's wallet signs an EIP-712 ApproveAgent message naming the agent's address.
  3. The server recovers the signer, checks it equals the claimed address, and submits the approval to Hyperliquid.
  4. 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

StepHyperliquid actionNotes
OpenupdateLeverage (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.
AdjustupdateIsolatedMargin (±)One action per call. Amounts are rounded to cents.
Closeorder (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.

ModeTrading 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.

  1. Sign an EIP-3009 ReceiveWithAuthorization on USDC, authorising the CctpExtension contract to pull the amount.
  2. Send CctpExtension.batchDepositForBurnWithAuth(auth, burn) on Arbitrum.
  3. Circle mints on HyperEVM and its CctpForwarder credits the recipient on HyperCore.
ContractChainAddress
USDC (native)Arbitrum One0xaf88d065e77c8cC2239327C5EDb3A432268e5831
CctpExtensionArbitrum One0xA95d9c1F655341597C94393fDdc30cf3c08E4fcE
CctpForwarderHyperEVM0xb21D281DEdb17AE5B501F6AA8256fe38C4e45757
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.

TestWhat it establishes
Liquidation priceAt the computed price, equity equals maintenance margin to nine decimal places, for longs and shorts.
Distance round triplev_for_distance(liq_distance(L)) = L for several leverages and both sides.
Distance against priceSection 4.2 agrees with section 4.1 for a 20x long.
Budget on addRising volatility adds margin and total commitment stays within the budget.
Removal floorA removal never leaves less than 10% of notional.
Bounded lossAcross 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:

Live result. A 10 USDC deposit made through the terminal was credited as 9.80 USDC:

Time (UTC)EventFromAmount
2026-11-26 19:31:51USDC credited to account 0x81f0…60f7Circle CoreDepositWallet 0x6b9e…0a249.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)ActionSizePriceNotionalFee
19:38:58Open long HYPE0.72$62.096$44.71$0.020119
19:39:21Close long HYPE0.72$62.080$44.70$0.020113
19:52:46Open long HYPE0.73$62.060$45.30$0.020386
19:53:27Close long HYPE0.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 describedP(reduce)Call
Far from liquidation, volatility falling, in profit6%UP
Far from liquidation, volatility steady, flat7%UP
Comfortable distance, at the target leverage8%UP
Close to liquidation, drifting against, small loss97%DOWN
Very close, volatility rising, large loss98%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.

CoinPolicyLiquidatedAvg $ in positionExposure keptMean PnL
BTCStatic 20x13.5%$48494%−$19
Cross, full budget0.0%$1,494100%−$13
Close and reopen0.0%$47388%−$15
Dynamic margin0.1%$65499%−$17
ETHStatic 20x30.0%$46184%−$21
Cross, full budget0.0%$1,494100%−$13
Close and reopen0.0%$45979%−$12
Dynamic margin2.9%$73396%−$18
SOLStatic 20x42.3%$42575%−$27
Cross, full budget0.0%$1,494100%−$13
Close and reopen0.0%$44474%−$17
Dynamic margin2.4%$80996%−$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

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

PropertyHow it is enforced
Ballast cannot withdraw user fundsHyperliquid does not permit agents to withdraw or transfer. Withdrawals need the owner's wallet signature.
One user cannot act for anotherPer-session agent keys. The approval signature must recover to the claimed address.
Other websites cannot send commandsState-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 exposedLocal wallet settings are ignored whenever the server is not bound to localhost.
The agent's spending is cappedMargin budget per position and a per-user position size cap, both checked in code before any action.
A wrong margin direction is containedThe position is re-read after every change. If leverage moved against the intended direction, the agent pauses.
Deposit funds cannot be misroutedForwarder 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

Leveraged trading can lose the entire margin posted to a position. Nothing in this document is financial advice.