# For Traders (Leaders)

## For Leaders (Traders)

Leaders create vaults and trade on Hyperliquid L1 through `HyperFunTrading.sol`.

***

### Create a Vault

#### Via UI (Recommended)

1. Go to [hypers.fun/launch](https://www.hypers.fun/launch)
2. Fill in vault details:
   * **Vault Name** - Your fund name
   * **Symbol** - 2-10 letter token symbol
   * **Performance Fee** - 0-30% (your cut of investor profits)
   * **Description** - Strategy description
   * **Image** - Vault logo
3. Connect wallet
4. Approve 1 USDC (L1 init fee)
5. Click "Create Token"

#### Via Contract

```solidity
factory.createVault(
    "Alpha Trading Vault",  // name
    "ATV",                  // symbol
    2000                    // 20% performance fee (bps)
);
```

***

### Performance Fee

#### How It Works

Performance fee is your reward for generating profits. It's **only charged when investors sell at a profit**.

```
Performance Fee = (Current NAV - Entry NAV) × Tokens × Fee Rate
```

#### Example

|                       | Value                |
| --------------------- | -------------------- |
| Investor buys at NAV  | $1.00                |
| Investor sells at NAV | $1.50                |
| Tokens sold           | 1,000                |
| Performance fee rate  | 20%                  |
| **Profit**            | $0.50 × 1,000 = $500 |
| **Your fee**          | $500 × 20% = $100    |

#### How You Receive It

Performance fee is **paid in vault tokens**, not USDC:

1. Investor calls `sell()`
2. Contract calculates profit
3. Fee tokens are **minted to you** (leader)
4. You can hold (benefit from future NAV growth) or sell for USDC

```solidity
// Event emitted when you receive performance fee
event PerformanceFeeMinted(
    address indexed user,      // Investor who sold
    address indexed leader,    // You
    uint256 feeTokens,         // Tokens minted to you
    uint256 nav                // NAV at the time
);
```

#### Maximizing Performance Fee

1. **Trade profitably** - Higher NAV = more profit for investors = more fee for you
2. **Attract long-term holders** - They accumulate more profit
3. **Build reputation** - Verified vaults attract more investors

#### Fee Calculation Code

```solidity
function _calculatePerformanceFee(
    address user,
    uint256 tokens,
    uint256 currentNav
) internal view returns (uint256 feeTokens) {
    EntryRecord storage record = entryRecords[user];

    // No profit = no fee
    if (currentNav <= record.weightedEntryNav) {
        return 0;
    }

    // Calculate profit per token
    uint256 profitPerToken = currentNav - record.weightedEntryNav;
    uint256 totalProfit = (tokens * profitPerToken) / PRECISION;

    // Your fee
    uint256 fee = (totalProfit * feeBps) / BPS;

    // Convert to tokens
    feeTokens = (fee * PRECISION) / currentNav;
}
```

***

### Trading Operations

#### Asset Indices

| Asset | Index     | szDecimals |
| ----- | --------- | ---------- |
| BTC   | 0         | 4          |
| ETH   | 1         | 3          |
| SOL   | 5         | 2          |
| SUI   | 30        | 1          |
| HIP-3 | >= 100000 | varies     |

#### Market Order

```solidity
function executeMarketOrder(
    uint32 asset,    // 0=BTC, 1=ETH, 5=SOL...
    bool isBuy,      // true=long, false=short
    uint64 size,     // Size in 1e8 format
    uint64 price     // Price with slippage (1e8 format)
) external;

// With custom leverage
function executeMarketOrder(
    uint32 asset,
    bool isBuy,
    uint64 size,
    uint64 price,
    uint32 leverage  // 1-50 (depends on asset)
) external;
```

**Example: Long 1 SOL at $150**

```javascript
await trading.executeMarketOrder(
    5,              // SOL
    true,           // long
    100000000,      // 1.0 SOL (1e8)
    15450000000     // $154.50 with 3% slippage (1e8)
);
```

#### Limit Order

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

// With custom leverage
function executeLimitOrder(
    uint32 asset,
    bool isBuy,
    uint64 size,
    uint64 price,
    uint32 leverage
) external;
```

#### Batch Orders (DCA / Split)

```solidity
function batchLimitOrders(
    uint32 asset,
    bool isBuy,
    uint64[] calldata sizes,
    uint64[] calldata prices,
    uint32 leverage
) external;
```

**Example: DCA into SOL**

```javascript
await trading.batchLimitOrders(
    5,                                      // SOL
    true,                                   // long
    [50000000, 50000000, 50000000],         // 0.5 SOL each
    [14500000000, 14000000000, 13500000000], // $145, $140, $135
    10                                      // 10x leverage
);
```

#### Close Position

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

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

#### Cancel Order

```solidity
function cancelOrder(uint32 asset, uint64 oid) external;
```

***

### HIP-3 Trading (Builder Perps)

For HIP-3 assets (index >= 100000), precompiles don't work. Must provide params from API.

#### Open Position

```solidity
function executeOrderBuilder(
    uint32 asset,           // e.g., 110003 for xyz:GOLD
    bool isBuy,
    uint64 size,
    uint64 price,
    uint32 szDecimals,      // From Hyperliquid API
    uint32 maxLeverage,     // From Hyperliquid API
    bool isLimit            // true=GTC, false=IOC
) external;
```

#### Close Position

```solidity
function closePositionBuilder(
    uint32 asset,
    bool isBuy,             // Opposite of position
    uint64 size,
    uint64 price,
    uint32 szDecimals
) external;
```

#### Get HIP-3 Asset Info

```javascript
// From Hyperliquid API
const response = await fetch('https://api.hyperliquid.xyz/info', {
  method: 'POST',
  body: JSON.stringify({ type: 'meta' })
});
const meta = await response.json();

// Find HIP-3 asset
const asset = meta.universe.find(a => a.name === 'xyz:GOLD');
console.log(asset.szDecimals);   // e.g., 0
console.log(asset.maxLeverage);  // e.g., 20
```

***

### API Wallets

API wallets allow automated trading bots to trade on your behalf.

#### Add API Wallet

```solidity
function addApiWallet(
    address apiWallet,
    string calldata name,
    uint256 durationDays    // 60-180 days, or 0 for unlimited
) external;
```

**Example:**

```javascript
await trading.addApiWallet(
    "0xBotAddress...",
    "Alpha Bot",
    90  // Expires in 90 days
);
```

#### Renew API Wallet

```solidity
function renewApiWallet(
    address apiWallet,
    uint256 durationDays
) external;
```

#### Remove API Wallet

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

#### Check Status

```solidity
function getApiWalletStatus(address apiWallet) external view returns (
    bool active,
    uint256 expiresAt,
    uint256 daysRemaining,
    string memory name
);
```

#### Security Notes

* API wallets can **only trade**, not withdraw funds
* Set expiration (60-180 days) for security
* Remove immediately if compromised
* L1 registration is permanent, but EVM check prevents unauthorized use

***

### Fund Management

#### Auto-Rebalance

Funds automatically rebalance between EVM and L1:

* **Target**: 50% EVM / 50% L1
* **Trigger**: When ratio goes below 48% or above 52%

#### Manual Transfers

```solidity
// L1 Spot → L1 Perp (before opening positions)
function transferToPerp(uint64 amount) external;

// L1 Perp → L1 Spot (after closing positions)
function transferFromPerp(uint64 amount) external;

// Sweep all withdrawable from Perp to Spot
function sweepToSpot() external;
function forceReturnToSpot() external;
```

#### Check Balances

```solidity
function getL1SpotBalance() public view returns (uint256);
function getL1AccountValue() public view returns (uint256);
function getTotalAssets() public view returns (uint256);

function getAccountMarginSummary() public view returns (
    int64 accountValue,
    uint64 marginUsed,
    uint64 ntlPos,
    int64 rawUsd
);
```

#### Check Positions

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

function getL1PositionFull(uint32 asset) public view returns (
    int64 szi,       // Size (+ = long, - = short)
    uint64 entryNtl  // Entry notional
);
```

***

### Leader Deposit

Leaders can deposit at NAV without bonding curve or trading fee:

```solidity
function deposit(uint256 usdcAmount) external;
```

**Example:**

```javascript
// Approve USDC
await usdc.approve(vaultAddress, amount);

// Deposit at NAV
await vault.deposit(amount);
```

> **Note:** Leaders are still subject to exit fees when selling.

***

### Update Metadata

```solidity
function setMetadataURI(string calldata _metadataURI) external;
```

**Example:**

```javascript
await vault.setMetadataURI("ipfs://QmYourNewMetadata...");
```

***

### View Your Earnings

#### Check Your Token Balance

```javascript
const balance = await vault.balanceOf(leaderAddress);
console.log(`Your tokens: ${ethers.formatEther(balance)}`);
```

#### Check Total Performance Fees Earned

Listen for `PerformanceFeeMinted` events:

```javascript
const filter = vault.filters.PerformanceFeeMinted(null, leaderAddress);
const events = await vault.queryFilter(filter);

let totalFeeTokens = 0n;
for (const event of events) {
    totalFeeTokens += event.args.feeTokens;
}
console.log(`Total fee tokens: ${ethers.formatEther(totalFeeTokens)}`);
```

#### Calculate USDC Value

```javascript
const nav = await vault.getNAV();
const usdcValue = (balance * nav) / ethers.parseEther("1");
console.log(`Value: $${ethers.formatUnits(usdcValue, 18)}`);
```

***

### Best Practices

#### Risk Management

1. **Don't over-leverage** - Leave margin buffer for volatility
2. **Use stop losses** - Close losing positions before liquidation
3. **Diversify** - Don't put all funds in one position
4. **Monitor reserve** - Keep enough EVM liquidity for redemptions

#### Building Trust

1. **Get verified** - Contact team to get verified badge
2. **Communicate** - Update description with strategy
3. **Be transparent** - Share trade history and reasoning
4. **Start small** - Build track record before scaling

#### Technical Tips

1. **Use limit orders** - Better prices than market orders
2. **Split large orders** - Reduce slippage with `batchLimitOrders`
3. **Check oracle price** - Before closing, verify `getOraclePrice(asset)`
4. **Monitor margin** - Use `getAccountMarginSummary()` regularly

***

### Related Pages

* Fund Creation - Detailed vault creation
* VaultTrading - Full trading API reference
* Contract Addresses - Deployed contracts
* Architecture - System overview


---

# 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/for-traders-leaders.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.
