> ## Documentation Index
> Fetch the complete documentation index at: https://scalarfield.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Hyperliquid Agent Architecture

> How automated strategy agents share one Hyperliquid account — per-agent position ledgers with signed quantities, hourly funding attribution, and pro-rata exchange-liquidation handling across and within agents.

<Info>**Prerequisites:** [Trading on Hyperliquid](/docs/trading/venues/hyperliquid) for order semantics and funding the account, [Strategies](/docs/trading/strategies) for the general agent model.</Info>

# Overview

All Scalar Field activity on Hyperliquid — chat trades and every strategy agent — settles into **one exchange account per user** (your EVM wallet address). The exchange only knows the account's *net* position per coin. Agent isolation is implemented on the platform side as a ledger:

* Each agent has its own **cash balance** and its own **position book** with **signed quantities** (negative = short).
* The sum of all agents' claims on a symbol, plus any **manual residual** (positions you hold outside of agents), must equal what the exchange actually holds. Reconciliation verifies this continuously.
* Agent NAV = `cash + sum(qty x mark price)`. Because quantities are signed, a short position contributes negative market value.

```mermaid theme={null}
flowchart TB
    subgraph account ["Your Hyperliquid Account (one EVM address)"]
        direction TB
        subgraph agentA ["Agent A"]
            bookA["H:BTC +0.02, H:ETH -0.5\nCash: $4,000"]
        end
        subgraph agentB ["Agent B"]
            bookB["H:BTC +0.01\nCash: $1,500"]
        end
        manual["Manual residual\n(chat trades / UI trades)"]
    end
    netPos["Exchange net position per coin"]
    account -->|"sum of signed claims"| netPos
    netPos -->|"reconciled every state read"| account
```

Two things live only at the **account level**, not per agent:

* **Margin and liquidation price.** The exchange computes `margin_used` and `liq_price` on the net account position. Agents do not carry their own margin model — an agent's NAV tracks entry/exit prices, fees, and funding, not free collateral.
* **Collateral buckets.** USDC sits in perps, spot, and HIP-3 builder-dex balances on the account. Agent cash is a bookkeeping ledger over that shared collateral, not a segregated wallet.

# Signed Fill Accounting

Every fill (agent order, reconciled external fill, or attributed liquidation) moves an agent's book with sign-aware transitions:

| Fill vs. current position     | Quantity after                | Average price           | Realized PnL                                                         |
| ----------------------------- | ----------------------------- | ----------------------- | -------------------------------------------------------------------- |
| Same direction (or from flat) | `current + fill`              | Volume-weighted average | 0                                                                    |
| Reducing                      | Moves toward zero             | Unchanged               | `closed_qty x (fill_px - avg_px)` for longs, sign-flipped for shorts |
| Crossing zero (flip)          | Remainder opens the other way | Fill price              | Full old leg realized                                                |

Cash moves with the fill: buys debit `qty x price` (plus fees), sells credit `qty x price` (minus fees). Fees always debit cash. Opening a short therefore *credits* cash while market value goes negative — NAV is unchanged at the moment of the fill, then tracks PnL.

# Funding

Hyperliquid settles funding **hourly** on every open perp position, crediting or debiting the account's USDC. Since the exchange settles at the account level, the platform mirrors each settlement onto the agents that held the position.

## Attribution across agents

Funding is attributed **per coin, pro-rata by signed quantity**, using the account's actual funding ledger (the `userFunding` events Hyperliquid records for each settlement):

```text theme={null}
per_unit(coin, hour) = usdc_settled / account_position_size
agent_delta          = agent_qty x sum(per_unit over unapplied hours)
```

Because the per-unit rate is derived from the real settlement, agents holding the same coin in the same direction split the payment exactly in proportion to their size, shorts receive the opposite sign of longs automatically, and the manual residual's share is never charged to any agent. If no ledger event is available for an hour (e.g. the account position was netted flat while an agent still held a claim), the platform falls back to the published hourly funding rate: `per_unit = -funding_rate x close price` (longs pay when the rate is positive).

## Watermarks within an agent

Each agent position carries a **funding watermark** — the timestamp through which funding has been applied:

* Hours are applied strictly after the watermark, then the watermark advances. A 2-minute settlement lag is left so an in-flight settlement is never half-counted.
* Opening a position from flat, or flipping direction, **resets the watermark to now** — an agent never pays funding for hours it did not hold.
* Accrual looks back at most **168 hours** (7 days); older unapplied hours are dropped rather than back-charged.

Applied funding lands in the agent's **cash** (and therefore its NAV) and accumulates in the position's `funding_paid` counter. Each application emits a `FUNDING_ACCRUED` event in `strategy.activity()`.

## When accrual runs

Accrual is lazy — nothing runs on a timer inside the agent. It triggers whenever the ledger is about to be read or changed:

```mermaid theme={null}
sequenceDiagram
    participant Agent as Strategy Agent
    participant Platform as Scalar Field
    participant HL as Hyperliquid

    Agent->>Platform: strategy.state() / strategy.execute()
    Platform->>HL: userFunding ledger since watermark
    HL-->>Platform: per-hour settlements (usdc, position size)
    Platform->>Platform: delta = agent_qty x sum(usdc / size)
    Platform->>Platform: cash += delta, funding_paid += delta, advance watermark
    Platform-->>Agent: state with funding reflected in cash / NAV
```

Trigger points: every `strategy.state()`, before every fill is applied, before a liquidation is attributed (funding is settled up to the liquidation timestamp first), and on unfreeze. If no hour boundary has passed since the watermark, the call is a no-op.

# Exchange Liquidation

There are two different things called "liquidation":

* `strategy.liquidate()` — a **voluntary flatten**: the agent submits closing orders through the normal execution path.
* **Exchange (forced) liquidation** — Hyperliquid force-closes part or all of the *account's* net position when margin runs out. This section covers the forced case.

## Detection

Forced closes happen outside any agent's order flow, so they surface as a divergence during reconciliation: the exchange's net quantity no longer matches the sum of agent claims. On Hyperliquid, any divergence beyond a `1e-6` quantity epsilon (in either direction — forced closes can hit longs or shorts) triggers a scan of the account's recent fills for entries carrying Hyperliquid's liquidation marker, looking back up to **72 hours**.

## Attribution across agents

Each liquidation fill is split among the agents holding the *liquidated direction*, plus the manual residual:

```text theme={null}
share = fill_size x |agent_qty| / (sum of same-direction agent claims + manual share)
```

The share is capped at the agent's own quantity, and the manual residual absorbs its proportion — agents are never assigned more than they held, and never pay for positions they did not claim.

## Application within an agent

For each attributed share, in order:

1. **Funding is settled first**, up to the liquidation timestamp, at the pre-liquidation quantity.
2. The share is applied as a **sign-correct close at the actual liquidation price**: a liquidated long realizes `share x (liq_px - avg_px)` and credits `share x liq_px` to cash; a liquidated short realizes `share x (avg_px - liq_px)` and debits the buyback cost. The agent's proportion of the liquidation fee is deducted from cash.
3. The close is recorded and the agent is **paused** with reason `account_liquidated` so it does not keep trading against a book that just changed underneath it.

```mermaid theme={null}
sequenceDiagram
    participant HL as Hyperliquid
    participant Platform as Scalar Field
    participant Agents as Agents on the account

    HL->>HL: Forced close of net position (margin call)
    Agents->>Platform: next strategy.state() / execute()
    Platform->>HL: fetch net position + agent claims comparison
    Platform->>Platform: divergence > epsilon detected
    Platform->>HL: fetch recent fills with liquidation marker
    Platform->>Platform: split each fill pro-rata across same-direction agents
    Platform->>Platform: per agent - settle funding, close at liq price, deduct fee share
    Platform->>Agents: record trade + LIQUIDATION_APPLIED, pause (account_liquidated)
```

## What you see

| Record                 | Content                                                                                                                                                                           |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Trade history          | A `FILLED` closing trade with reason `EXCHANGE_LIQUIDATION` at the actual liquidation price                                                                                       |
| `strategy.activity()`  | A `LIQUIDATION_APPLIED` event with quantity, price, realized PnL, cash delta, and fee share                                                                                       |
| Agent status           | Paused with reason `account_liquidated`; state reads return `tradable: false` with `block_reason: ACCOUNT_LIQUIDATED`                                                             |
| Unexplained divergence | If the mismatch cannot be explained by liquidation fills, the standard freeze applies (`STRATEGY_FROZEN_RECONCILIATION_MISMATCH`) — see [Reconciliation](/docs/trading/reconciliation) |

Attribution is idempotent: each exchange fill is applied to an agent at most once, so repeated reconciliations never double-count.

# Parameters

| Parameter                                      | Value                                                                                                       |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Funding settlement cadence                     | Hourly (Hyperliquid native)                                                                                 |
| Funding settlement lag before applying an hour | 2 minutes                                                                                                   |
| Maximum funding lookback                       | 168 hours                                                                                                   |
| Maximum liquidation-fill lookback              | 72 hours                                                                                                    |
| Reconciliation quantity epsilon                | 1e-6                                                                                                        |
| Settlement grace before freeze (Hyperliquid)   | 2 minutes                                                                                                   |
| Unfreeze close pricing                         | VWAP of the account's covering fills when they explain at least 95% of the divergence; mark price otherwise |
| Minimum order value (strategy execution)       | \$1.00                                                                                                      |
| Default market-order slippage                  | 50 bps                                                                                                      |
| Minimum deposit to the exchange                | \$5 USDC                                                                                                    |
| Withdrawal fee (to Arbitrum)                   | \$1 USDC                                                                                                    |

# HIP-3 Builder Dexs

Hyperliquid's HIP-3 builder-deployed perp dexs (symbols `H:<dex>:<coin>`, e.g. `H:xyz:AAPL`) hold their own USDC collateral in separate clearinghouses on the same account:

* **Account values aggregate them.** `venue.account(account="HYPERLIQUID")` reports `account_value`, `margin_used`, and `portfolio_value` summed across the main dex and every HIP-3 dex, with per-dex USDC balance rows tagged with a `dex` key.
* **Agent ledgers are symbol-keyed**, so HIP-3 positions flow through the same signed-fill, funding, and liquidation-attribution paths as main-dex perps — the dex only determines which collateral bucket backs the position at the exchange.
* Moving USDC between the spot, main perps, and HIP-3 buckets is a transfer on the account (done from the portfolio page), not an agent operation.

# Related

* [Trading on Hyperliquid](/docs/trading/venues/hyperliquid) — order semantics, account structure, funding the account
* [Strategies](/docs/trading/strategies) — the general agent model and `strategy.*` API
* [Reconciliation](/docs/trading/reconciliation) — aggregate verification and the freeze/unfreeze flow
* [Hyperliquid Data](/docs/market-data/hyperliquid-data) — funding rates, positions, and fills for any wallet
