# HyperFunTrading API

## HyperFunTrading API Documentation

### Overview

HyperFunTrading is the trading module for HyperFun vaults on Hyperliquid. It handles:

* Perpetual trading (open/close positions)
* L1 fund transfers (Spot ↔ Perp)
* Auto-rebalancing (EVM ↔ L1)
* API wallet management

**Contract Address**: Deployed as a proxy for each vault (get from `vault.tradingModule()`)

***

### Constants

<table><thead><tr><th>Name</th><th width="385.6666259765625">Value</th><th>Description</th></tr></thead><tbody><tr><td>USDC</td><td><code>0xb88339CB7199b77E23DB6E890353E22632Ba630f</code></td><td>USDC token on HyperEVM</td></tr><tr><td>CORE_DEPOSIT_WALLET</td><td><code>0x6B9E773128f453f5c2C60935Ee2DE2CBc5390A24</code></td><td>For EVM → L1 deposits</td></tr></tbody></table>

#### Asset Indices (Hyperliquid Perps)

| Asset | Index | szDecimals | Max Leverage |
| ----- | ----- | ---------- | ------------ |
| BTC   | 0     | 5          | 50x          |
| ETH   | 1     | 4          | 50x          |
| SOL   | 5     | 2          | 20x          |
| SUI   | 57    | 1          | 20x          |
| HYPE  | 132   | 1          | 20x          |

***

### Authorization

| Role           | Can Call                                        |
| -------------- | ----------------------------------------------- |
| **Leader**     | All trading functions, API wallet management    |
| **API Wallet** | All trading functions (if active & not expired) |
| **Admin**      | Fund withdrawals, refill reserve                |
| **Vault**      | `autoRebalance()` only                          |

***

### Trading Functions

#### executeMarketOrder

Execute a market order with IOC (Immediate-Or-Cancel).

```solidity
function executeMarketOrder(
    uint32 asset,      // Asset index (0=BTC, 1=ETH, 5=SOL, etc.)
    bool isBuy,        // true=LONG, false=SHORT
    uint64 size,       // Size in 1e8 format (1.5 SOL = 150000000)
    uint64 price       // Price in 1e8 format with 3% slippage
) external
```

**With custom leverage:**

```solidity
function executeMarketOrder(
    uint32 asset,
    bool isBuy,
    uint64 size,
    uint64 price,
    uint32 leverage    // 1 to maxLeverage, 0 = use max
) external
```

**Example (Python/JS):**

```javascript
// Long 1.5 SOL at $150 with 3% slippage
const asset = 5;  // SOL
const isBuy = true;
const size = 150000000;  // 1.5 * 1e8
const price = 15450000000;  // $154.50 * 1e8 (with slippage)
const leverage = 10;

await trading.executeMarketOrder(asset, isBuy, size, price, leverage);
```

***

#### executeLimitOrder

Execute a limit order with GTC (Good-Till-Cancel).

```solidity
function executeLimitOrder(
    uint32 asset,
    bool isBuy,
    uint64 size,       // Size in 1e8 format
    uint64 price       // Exact limit price in 1e8 format
) external
```

**With custom leverage:**

```solidity
function executeLimitOrder(
    uint32 asset,
    bool isBuy,
    uint64 size,
    uint64 price,
    uint32 leverage
) external
```

***

#### executeLimitOrderRaw

Execute limit order WITHOUT margin check. Use for split orders to avoid multiple L1 actions per TX.

```solidity
function executeLimitOrderRaw(
    uint32 asset,
    bool isBuy,
    uint64 size,
    uint64 price
) external
```

**Important:** Caller must ensure margin is pre-transferred to L1 Perp before calling.

***

#### batchLimitOrders

Execute multiple limit orders in one transaction (for DCA / split orders).

```solidity
function batchLimitOrders(
    uint32 asset,
    bool isBuy,
    uint64[] calldata sizes,   // Array of sizes
    uint64[] calldata prices,  // Array of prices (same length)
    uint32 leverage
) external
```

**Limits:** 1-20 orders per batch.

**Example:**

```javascript
// Place 3 limit buy orders for SOL at different prices
const sizes = [50000000, 50000000, 50000000];  // 0.5 SOL each
const prices = [14800000000, 14900000000, 15000000000];  // $148, $149, $150

await trading.batchLimitOrders(5, true, sizes, prices, 10);
```

***

#### closePositionAdvanced

Close a position using oracle price with slippage.

```solidity
function closePositionAdvanced(
    uint32 asset,
    uint32 slippageBps,  // 100-5000 (1%-50%)
    bool reduceOnly      // true = won't flip position
) external
```

**Example:**

```javascript
// Close SOL position with 3% slippage
await trading.closePositionAdvanced(5, 300, true);
```

***

#### executeCloseOrderAdvanced

Close with custom size and price (for partial closes).

```solidity
function executeCloseOrderAdvanced(
    uint32 asset,
    bool isBuy,          // Opposite of position direction
    uint64 size,
    uint64 price,
    bool reduceOnly
) external
```

***

#### cancelOrder

Cancel a pending limit order.

```solidity
function cancelOrder(
    uint32 asset,
    uint64 oid          // Order ID from Hyperliquid API
) external
```

***

### Fund Transfer Functions

#### transferToPerp

Transfer USDC from L1 Spot to L1 Perp.

```solidity
function transferToPerp(uint64 amount) external  // amount in 6 decimals
```

#### transferFromPerp

Transfer USDC from L1 Perp to L1 Spot.

```solidity
function transferFromPerp(uint64 amount) external  // amount in 6 decimals
```

#### sweepToSpot

Sweep all withdrawable funds from Perp to Spot.

```solidity
function sweepToSpot() external
```

#### forceReturnToSpot

Force return all withdrawable from Perp to Spot (use if sweepToSpot doesn't work).

```solidity
function forceReturnToSpot() external
```

***

### View Functions

#### getL1Position

Get current position size for an asset.

```solidity
function getL1Position(uint32 asset) external view returns (int64 szi)
```

**Returns:** Position size in szDecimals format.

* Positive = LONG
* Negative = SHORT
* For SOL (szDecimals=2): `szi=150` means 1.5 SOL

#### getL1PositionFull

Get full position data.

```solidity
function getL1PositionFull(uint32 asset) external view returns (
    int64 szi,       // Position size in szDecimals
    uint64 entryNtl  // Entry notional in 1e6
)
```

#### getL1SpotBalance

Get L1 Spot USDC balance.

```solidity
function getL1SpotBalance() external view returns (uint256)  // 6 decimals
```

#### getL1AccountValue

Get L1 Perp account value (includes unrealized PnL).

```solidity
function getL1AccountValue() external view returns (uint256)  // 6 decimals
```

#### getAccountMarginSummary

Get detailed margin info.

```solidity
function getAccountMarginSummary() external view returns (
    int64 accountValue,   // Total account value
    uint64 marginUsed,    // Margin used by positions
    uint64 ntlPos,        // Total notional position
    int64 rawUsd          // Raw USD balance
)
```

#### getOraclePrice

Get current oracle price for an asset.

```solidity
function getOraclePrice(uint32 asset) external view returns (uint64)
```

**Format:** `price_USD * 10^(6-szDecimals)`

#### getSzDecimals

Get size decimals for an asset.

```solidity
function getSzDecimals(uint32 asset) external view returns (uint32)
```

#### getMaxLeverage

Get maximum leverage for an asset.

```solidity
function getMaxLeverage(uint32 asset) external view returns (uint32)
```

#### previewNormalizedSize

Preview how size will be normalized (rounded).

```solidity
function previewNormalizedSize(uint32 asset, uint64 size) external view returns (
    uint64 normalizedSize,  // Actual size after rounding
    uint32 szDecimals,      // Asset's szDecimals
    uint64 minSize          // Minimum valid size
)
```

#### getTotalAssets

Get total vault assets (EVM + L1 Spot + L1 Perp - Pending Sells).

```solidity
function getTotalAssets() external view returns (uint256)  // 18 decimals
```

#### checkReserve

Check if EVM reserve is low.

```solidity
function checkReserve() external view returns (bool isLow)
```

***

### API Wallet Setup (Complete Flow)

#### Overview

AI/Bot 要交易需要完成以下步骤：

```
┌─────────────────────────────────────────────────────────────┐
│  Step 1: Leader 添加 API Wallet                              │
│  trading.addApiWallet(botAddress, "MyBot", 90)              │
│  → 在 EVM 上记录                                             │
│  → 自动在 L1 上注册 (ACTION_ADD_API_WALLET)                  │
├─────────────────────────────────────────────────────────────┤
│  Step 2: 设置 Builder Fee (可选，用于交易返佣)               │
│  token.approveBuilderFee(builderAddress, 50)                │
│  → 允许指定 builder 收取交易手续费返佣                        │
├─────────────────────────────────────────────────────────────┤
│  Step 3: API Wallet 可以开始交易                             │
│  trading.executeMarketOrder(...)                            │
└─────────────────────────────────────────────────────────────┘
```

#### Step 1: addApiWallet (Required)

Leader 添加 API wallet，同时在 EVM 和 L1 上注册。

```solidity
function addApiWallet(
    address apiWallet,      // Bot/AI 的钱包地址
    string calldata name,   // 名称 (显示在 Hyperliquid)
    uint256 durationDays    // 60-180 天，或 0 = 永久
) external
```

**Example:**

```javascript
// Leader 调用
await trading.addApiWallet(
    "0xYourBotAddress",
    "TradingBot-v1",
    90  // 90天有效期
);
```

**权限:** 仅 Leader 可调用

**L1 Action:** 自动发送 `ACTION_ADD_API_WALLET` 到 Hyperliquid

***

#### Step 2: approveBuilderFee (Optional)

设置交易手续费返佣（如果需要）。这是在 **Token 合约** 上调用，不是 Trading。

```solidity
// 在 HyperFunToken 合约上
function approveBuilderFee(
    address builder,       // Builder 地址
    uint64 maxFeeRate      // Fee rate in decibps (50 = 0.05%)
) external
```

**谁可以调用:**

* Admin
* Factory Owner
* Factory 合约本身

**Note:** 如果 Factory 设置了 `defaultBuilder`，新创建的 vault 会自动 approve。

***

#### Step 3: API Wallet 开始交易

API Wallet 现在可以调用所有交易函数：

```javascript
// API Wallet (Bot) 调用
const tradingWithBot = trading.connect(botSigner);

// 开仓
await tradingWithBot.executeMarketOrder(5, true, 100000000, price);

// 平仓
await tradingWithBot.closePositionAdvanced(5, 300, true);
```

***

#### API Wallet Management Functions

**renewApiWallet**

续期 API wallet（Leader only）。

```solidity
function renewApiWallet(
    address apiWallet,
    uint256 durationDays   // 60-180 days, or 0 for unlimited
) external
```

**removeApiWallet**

移除 API wallet 授权（Leader only）。

```solidity
function removeApiWallet(address apiWallet) external
```

**Note:** L1 上的注册无法移除（Hyperliquid 限制），但 EVM 上的检查会阻止交易。

**getApiWalletStatus**

获取 API wallet 状态。

```solidity
function getApiWalletStatus(address apiWallet) external view returns (
    bool active,           // 是否有效
    uint256 expiresAt,     // 过期时间戳
    uint256 daysRemaining, // 剩余天数
    string memory name     // 名称
)
```

**isApiWalletValid**

检查 API wallet 是否有效。

```solidity
function isApiWalletValid(address wallet) external view returns (bool)
```

***

#### Complete Setup Example

```javascript
const { ethers } = require("ethers");

// Contracts
const tokenAbi = [...];   // HyperFunToken ABI
const tradingAbi = [...]; // HyperFunTrading ABI

const token = new ethers.Contract(vaultAddress, tokenAbi, leaderSigner);
const trading = new ethers.Contract(tradingAddress, tradingAbi, leaderSigner);

// Step 1: Add API Wallet (Leader)
const botAddress = "0xYourBotAddress";
await trading.addApiWallet(botAddress, "AI-Trader", 90);
console.log("API Wallet added!");

// Step 2: Approve Builder Fee (Optional, Admin/Factory Owner)
// Usually done by Factory automatically
// await token.approveBuilderFee(builderAddress, 50);

// Step 3: Verify setup
const status = await trading.getApiWalletStatus(botAddress);
console.log("Active:", status.active);
console.log("Expires:", new Date(status.expiresAt * 1000));
console.log("Days remaining:", status.daysRemaining.toString());

// Step 4: Bot can now trade
const tradingWithBot = trading.connect(botSigner);
const isValid = await tradingWithBot.isApiWalletValid(botAddress);
console.log("Bot authorized:", isValid);

// Execute trade as bot
await tradingWithBot.executeMarketOrder(5, true, 100000000, 15450000000, 10);
```

***

### Admin Functions (Admin Only)

#### withdrawPerpToEVM

Withdraw USDC from L1 Perp to EVM.

```solidity
function withdrawPerpToEVM(uint64 amount) external  // 6 decimals
```

#### withdrawAllPerpToEVM

Withdraw all withdrawable from L1 Perp to EVM.

```solidity
function withdrawAllPerpToEVM() external
```

#### withdrawAllSpotToEVM

Send all L1 Spot USDC to EVM.

```solidity
function withdrawAllSpotToEVM() external
```

#### refillReserve

Refill EVM reserve from L1 Perp.

```solidity
function refillReserve(uint64 amount) external
```

***

### Size & Price Formatting

#### Size Format (1e8)

All sizes are in **1e8 format** (8 decimal places):

| Amount    | Size Value  |
| --------- | ----------- |
| 1.0 SOL   | `100000000` |
| 0.5 ETH   | `50000000`  |
| 0.001 BTC | `100000`    |

**Important:** Sizes are normalized based on `szDecimals`:

* SOL (szDecimals=2): Minimum = 0.01 SOL = `1000000`
* ETH (szDecimals=4): Minimum = 0.0001 ETH = `10000`
* BTC (szDecimals=5): Minimum = 0.00001 BTC = `1000`

#### Price Format (1e8)

All prices are in **1e8 format**:

| Price     | Price Value     |
| --------- | --------------- |
| $150.00   | `15000000000`   |
| $3000.50  | `300050000000`  |
| $95000.00 | `9500000000000` |

***

### Events

```solidity
event OrderSent(uint32 indexed asset, bool isBuy, uint64 size, uint64 price);
event OrderCancelled(uint32 indexed asset, uint64 oid);
event ApiWalletAdded(address indexed apiWallet, string name, uint256 expiresAt);
event ApiWalletRemoved(address indexed apiWallet);
event ApiWalletRenewed(address indexed apiWallet, uint256 newExpiresAt);
event FundsTransferred(bool toPerp, uint64 amount);
event WithdrawnFromL1(uint256 amount);
event Rebalanced(bool toL1, uint256 amount, uint256 newRatioBps);
event DepositedToL1(uint256 amount);
event ReserveLow(uint256 currentBalance, uint256 totalAssets);
```

***

### Example: Full Trading Flow

```javascript
const { ethers } = require("ethers");

// Connect to trading module
const tradingAbi = [...]; // Use HyperFunTrading ABI
const trading = new ethers.Contract(tradingAddress, tradingAbi, signer);

// 1. Check current position
const position = await trading.getL1Position(5);  // SOL
console.log("Current SOL position:", position.toString());

// 2. Check balances
const spotBalance = await trading.getL1SpotBalance();
const perpValue = await trading.getL1AccountValue();
console.log("L1 Spot:", spotBalance / 1e6, "USDC");
console.log("L1 Perp:", perpValue / 1e6, "USDC");

// 3. Get oracle price
const oraclePrice = await trading.getOraclePrice(5);
const szDec = await trading.getSzDecimals(5);
const priceUsd = oraclePrice / Math.pow(10, 6 - szDec);
console.log("SOL Price:", priceUsd);

// 4. Open position
const size = 100000000;  // 1.0 SOL
const price = Math.floor(priceUsd * 1.03 * 1e8);  // +3% slippage
await trading.executeMarketOrder(5, true, size, price, 10);

// 5. Close position
await trading.closePositionAdvanced(5, 300, true);  // 3% slippage
```

***

### Error Codes

| Code                    | Meaning                              |
| ----------------------- | ------------------------------------ |
| `Not authorized`        | Caller is not leader/API wallet      |
| `Not admin`             | Caller is not admin                  |
| `No deposits`           | Vault has no deposits yet            |
| `Size too small`        | Size below minimum for asset         |
| `No L1 position`        | No position to close                 |
| `Slippage 1-50%`        | Invalid slippage value               |
| `Array length mismatch` | Batch order arrays different lengths |
| `Invalid order count`   | Batch must be 1-20 orders            |

***

### Contract Version

Current: **V44** (includes pending sell fix)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hyper-fun.gitbook.io/hypers.fun/how-it-works/hyperfuntrading-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
