# About AFX

AFX is a high-performance sovereign L1 purpose-built for decentralized derivatives. By synthesizing the rapid execution of a centralized exchange with the immutable sovereignty of the blockchain, AFX delivers a professional-grade **Perp DEX** environment characterized by sub-100ms finality, institutional liquidity, and unmatched capital efficiency.

## Why AFX

* **On-Chain Verifiable** — Every order match and settlement is verifiable on the blockchain. Your funds stay in your control; the platform cannot misappropriate assets.
* **High-Performance Trading** — Everything runs fully on-chain: matching and settlement happen on-chain, delivering the speed, depth, and reliability traders expect from professional derivatives infrastructure, without giving up self-custody or transparency.
* **Fair & Manipulation-Resistant Pricing** — Mark price is derived from the median of three independent price components, combining on-chain order book data with multi-exchange oracle feeds to resist price manipulation.
* **Institutional-Grade Risk Controls** — Tiered margin requirements, multi-phase liquidation, and an LP Vault backstop ensure platform solvency even in extreme market conditions.

## At a Glance

|                         |                                                                                                         |
| ----------------------- | ------------------------------------------------------------------------------------------------------- |
| **Network**             | Our Own Layer 1                                                                                         |
| **Settlement Currency** | USDC                                                                                                    |
| **Contract Type**       | USDC-margined linear perpetual                                                                          |
| **Supported Assets**    | Crypto, commodity, equity, and ETF perpetual markets. Query live product metadata for the current list. |
| **Max Leverage**        | Up to 100x                                                                                              |
| **Trading Fees**        | Taker 0.06% · Maker 0.01%                                                                               |
| **Funding Interval**    | Every 4 hours (varies by asset)                                                                         |
| **Trading Hours**       | 24/7                                                                                                    |

## Getting Started

1. **Connect** — Log in with your email or connect a Web3 wallet (MetaMask, WalletConnect, OKX Wallet, Coinbase Wallet, etc.).
2. **Deposit** — Transfer USDC to your AFX trading account via the Arbitrum network.
3. **Trade** — Select a trading pair, set your leverage, and place your order.

## Core Features

### Trading

AFX supports market, limit, conditional (stop), and TWAP-style execution. Traders can choose between cross margin and isolated margin, and trade in one-way or hedge (two-way) position mode where available. Maximum leverage is determined per market and risk tier.

* [Trading Rules](/trading-rules)
* [Order Types](/trading-rules/order-types)
* [Leverage](/trading-rules/leverage)

### Pricing & Funding

Mark price uses a three-component median to ensure fair valuation. Oracle price aggregates spot prices from Binance, Bybit, and OKX with multi-layer protection. Funding rates anchor perpetual prices to the underlying spot market.

* [Mark Price](/trading-rules/mark-price)
* [Oracle Price](/trading-rules/oracle-price)
* [Funding Rate](/trading-rules/funding-rate)

### Risk & Liquidation

A tiered risk limit system adjusts margin requirements by position size. Liquidation follows a four-phase process: order cancellation, market close, LP Vault takeover, and auto-deleveraging (ADL) as a last resort.

* [Risk Limits](/trading-rules/risk-limits)
* [Liquidation](/trading-rules/liquidation)
* [ADL](/trading-rules/adl)

### Vaults

The **LP Vault (ALP)** is the protocol-level liquidity vault — 0% management fee, open to all depositors. **User Vaults** let any trader create a strategy vault and earn a 10% profit share from depositors.

* [Vaults Overview](/vaults)
* [LP Vault](/vaults/lp-vault)

### Earn & Grow

Invite traders through the **Affiliate Program** and earn 10%–35% commission on their trading fees. Active traders can join the **VIP Program** to receive a share of the platform's fee revenue.

* [Affiliate Program](/affiliate-program)
* [VIP Program](/vip-program)

## Documentation

| Section                                             | What You'll Learn                                                               |
| --------------------------------------------------- | ------------------------------------------------------------------------------- |
| [Trading Rules](/trading-rules)                     | Margin modes, position modes, order types, leverage, TP/SL, slippage protection |
| [Mark Price](/trading-rules/mark-price)             | How AFX calculates the fair mark price                                          |
| [Oracle Price](/trading-rules/oracle-price)         | Oracle sources, protection mechanisms                                           |
| [Funding Rate](/trading-rules/funding-rate)         | Funding formula, premium index, settlement schedule                             |
| [Liquidation](/trading-rules/liquidation)           | When and how positions are liquidated                                           |
| [Risk Limits](/trading-rules/risk-limits)           | Tiered leverage and maintenance margin                                          |
| [Supported Assets](/trading-rules/supported-assets) | All trading pairs and their parameters                                          |
| [Vaults](/vaults)                                   | LP Vault and User Vault mechanics                                               |
| [Affiliate Program](/affiliate-program)             | Referral commissions (10%–35%)                                                  |
| [VIP Program](/vip-program)                         | Fee revenue sharing for active traders                                          |

## Links

* **Trade:** <https://app.afx.xyz/trade>
* **Discord:** [AFX\_XYZ](https://discord.gg/mUeDkWYENJ)
* **Twitter / X:** [@AFX\_XYZ](https://x.com/AFX_XYZ)
* **Medium:** <https://medium.com/@AFXTrade>


# Core contributors

The growth of AFX has been supported by a wide range of experienced native crypto participants operating in the industry since 2018. The collective experience of these contributors ranges from DeFi, to centralised exchanges, fiat on-ramps, and traditional finance.

Perpetual DEXes represent one of the most actively developing sectors in crypto. This is why AFX was built from the ground up: to deliver a comprehensive and highly rewarding trading experience for traders who want to join and grow alongside a novel protocol from its earliest stages. The decision to build a dedicated decentralized Layer 1 with a native order book DEX was informed by the observed limitations of existing L1s in areas such as business models, scalability, and security.

AFX's users play an important role in shaping the platform's development.. Core contributors engage with traders daily, actively reviewing suggestions and feedback. You are welcome to join the [Discord Server](https://discord.com/invite/mUeDkWYENJ). AFX is fully self-funded and remains free from external investor pressure regarding product direction or scaling decisions.


# Deposit

AFX accepts one asset on one network: USDC on Arbitrum. Here is how to get it there from any starting point, and how to avoid the mistakes that trip people up.

AFX accepts a single deposit asset on a single network: USDC over the Arbitrum network. Every deposit, whether it comes from a wallet, a centralized exchange, or another chain, has to arrive as USDC on Arbitrum before it is credited to your AFX trading account.Most failed deposits trace back to the same few mistakes: the wrong token, or the wrong network. This guide covers the correct flow from every common starting point, and how to recover if something goes wrong.

### The One Rule

AFX runs on its own Layer 1. Matching and settlement happen on-chain on the AFX network. Arbitrum is the network used for deposits and withdrawals only, and USDC is the settlement currency for the entire platform, since every perpetual contract on AFX is USDC-margined.Every deposit question therefore reduces to one step: get USDC onto Arbitrum in a wallet you control, then deposit through the AFX app.Two things to keep in mind before you start:

* **USDC only -** USDT, ETH, ARB, or any other token will not be credited.
* **Arbitrum only -** USDC on Ethereum, Solana, Base, or any other network has to be bridged to Arbitrum first.

### Step 1: Connect

Go to[ app.afx.xyz/trade](https://app.afx.xyz/trade) and log in with your email, or connect a Web3 wallet such as MetaMask, WalletConnect, OKX Wallet, or Coinbase Wallet.If you connect a Web3 wallet, set it to the Arbitrum One network before depositing.

### Step 2: Get USDC on Arbitrum

How you do this depends on where your funds are starting from:**From a centralized exchange.**&#x54;his is the simplest route for most people, and also where wrong-network mistakes happen most often. On your exchange's withdrawal page, select USDC, then select Arbitrum One as the withdrawal network. It is sometimes listed as "Arbitrum." Do not select Ethereum, BNB Chain, Solana, or any other network. Withdraw to your own Arbitrum wallet address, and confirm the funds arrive before continuing. If your exchange does not support Arbitrum withdrawals for USDC, withdraw to Ethereum first and bridge from there.\
**From Ethereum.**&#x55;se a bridge that moves USDC from Ethereum to Arbitrum, such as the official Arbitrum Bridge. Select USDC on Ethereum as the source and USDC on Arbitrum as the destination, confirm the transaction, and verify the funds arrive on Arbitrum before continuing.\
**From another chain.**&#x55;se a cross-chain bridge that supports your source chain to Arbitrum USDC. Set the destination to your Arbitrum wallet address, and confirm arrival before continuing. Note that Solana USDC cannot be sent directly to an Arbitrum address; Solana and Arbitrum use different token standards, so the bridge step is required.<br>

### Step 3: Deposit

Once you have USDC in your Arbitrum wallet:

1. On[ app.afx.xyz/trade](https://app.afx.xyz/trade), click Deposit.
2. Confirm your wallet is on the Arbitrum One network.
3. Enter the USDC amount and confirm the transaction in your wallet.
4. Your balance is credited to your AFX trading account.

Once credited, your USDC is available as margin across all markets, in either cross or isolated margin mode. How margin works across your positions is covered in[ Cross Margin vs Isolated Margin](https://medium.com/@AFXTrade/cross-margin-vs-isolated-margin-choosing-your-risk-profile-de67b5a5af97).<br>

### Common Mistakes and Recovery

\
**Wrong network selected on an exchange withdrawal.**&#x49;f you selected Ethereum instead of Arbitrum, your USDC arrived on Ethereum mainnet at the same wallet address. The funds are not lost. Switch your wallet to Ethereum, confirm the balance, bridge it to Arbitrum, and deposit normally.\
**Wrong token sent.**&#x55;SDT and other tokens are not credited. If the tokens are sitting in your own Arbitrum wallet, swap them for USDC on an Arbitrum DEX and deposit the USDC.\
**Deposit confirmed on-chain but not credited.**&#x56;erify the deposit was sent from the same wallet connected to AFX. If it still does not appear, reach out through the official support channels.\
**Deposit appears smaller than expected.**&#x49;f you hold open cross-margin positions with unrealized losses, a new deposit goes toward the collateral backing those positions. Check your full margin overview, not only your available balance.

### Withdrawals

\
Withdrawals follow the same route in reverse: USDC leaves your AFX trading account and arrives in your wallet on the Arbitrum network. From there, funds can be bridged to any chain, or sent to an exchange that supports Arbitrum deposits.

### FAQ

\
**What can I deposit to AFX?**&#x55;SDC only, over the Arbitrum network. Every AFX perpetual contract is USDC-margined.\
**Can I deposit directly from Binance, OKX, or Coinbase?**&#x59;es. Withdraw USDC to your own wallet using the Arbitrum One network, then deposit from your wallet into AFX.\
**Is AFX built on Arbitrum?**&#x4E;o. AFX runs on its own Layer 1, and matching and settlement happen on-chain on the AFX network. Arbitrum is the network used for deposits and withdrawals only.

***

\
**Trade:**[ app.afx.xyz/trade](https://app.afx.xyz/trade)

**Join the conversation:**[ Discord](https://discord.gg/mUeDkWYENJ) ·[ @AFX\_XYZ](https://x.com/AFX_XYZ)


# Trading Rules


# Supported Assets

AFX supports USDC-margined linear perpetual contracts on the AFX Layer 1 network. All contracts are quoted and settled in USDC.

## Source of Truth

The available markets, symbol codes, precision, leverage limits, fee rates, funding intervals, and risk tiers can change as new markets are listed or parameters are updated.

Always query the live product metadata before trading:

```
GET /info/public/product-meta
```

Use the response to resolve:

| Field             | Meaning                                                |
| ----------------- | ------------------------------------------------------ |
| `symbol`          | Trading pair, such as `BTCUSDC`                        |
| `code`            | Numeric symbol code used by API order endpoints        |
| `listStatus`      | Current listing status                                 |
| `maxLeverage`     | Highest leverage available before risk-tier reductions |
| `marginTableId`   | Risk table used for leverage and maintenance margin    |
| `tickSize`        | Minimum price increment                                |
| `stepSize`        | Minimum quantity increment                             |
| `minOrderValue`   | Minimum notional order value                           |
| `fundingInterval` | Funding interval in seconds                            |

## Example Listed Markets

The following examples reflect the live metadata shape, but they are not a complete market list. Query `product-meta` for the current values before placing orders.

| Symbol  | Symbol Code | Base Asset | Max Leverage | Funding Interval | Settlement |
| ------- | ----------- | ---------- | ------------ | ---------------- | ---------- |
| BTCUSDC | 1           | BTC        | 100x         | 4 hours          | USDC       |
| ETHUSDC | 2           | ETH        | 100x         | 4 hours          | USDC       |
| XAUUSDC | 3           | XAU        | 25x          | 4 hours          | USDC       |
| CLUSDC  | 4           | CL         | 25x          | 4 hours          | USDC       |
| SOLUSDC | 5           | SOL        | 25x          | 4 hours          | USDC       |
| XRPUSDC | 6           | XRP        | 25x          | 4 hours          | USDC       |

## Oracle Price Sources

Each trading pair derives its Oracle Price from external market prices with protection rules designed to reduce manipulation risk. Source venues and weights may vary by market type.

For details on how the Oracle Price is calculated and protected, see [Oracle Price](/trading-rules/oracle-price).


# Leverage

AFX offers adjustable leverage for all perpetual contracts. The maximum leverage available depends on the asset tier and your notional position size.

## Leverage Settings

* Leverage is set **per trading pair**.
* In Hedge Mode, long and short positions on the same pair share the same leverage setting.
* Leverage can be adjusted at any time, including when you have open positions or orders.
* When adjusting leverage on an existing isolated position, additional margin may be transferred from your available balance, or excess margin may be released.

## Maximum Leverage by Market

Maximum leverage decreases as your position size increases. The current leverage cap for each market is returned by live product metadata:

```
GET /info/public/product-meta
```

Use the `maxLeverage` and `marginTableId` fields together with [Risk Limits](/trading-rules/risk-limits). Do not hardcode symbol codes or leverage tiers in trading systems; listed markets and risk parameters can expand over time.

Example current maximum leverage values:

| Example Market | Max Leverage |
| -------------- | ------------ |
| BTCUSDC        | Up to 100x   |
| ETHUSDC        | Up to 100x   |
| XAUUSDC        | Up to 25x    |
| CLUSDC         | Up to 25x    |
| SOLUSDC        | Up to 25x    |
| XRPUSDC        | Up to 25x    |

## Leverage Adjustment Rules

**No open positions or orders:**

* Simply select your desired leverage. The system shows the corresponding maximum position size.

**With open positions or orders:**

* A risk notice is displayed when adjusting leverage.
* Increasing leverage: The initial margin requirement decreases; excess margin is released back to your available balance (isolated) or remains in the shared pool (cross).
* Decreasing leverage: Additional margin is required. If your available balance is insufficient, the adjustment will fail — you must either deposit more funds or reduce your position first.
* If the selected leverage is too low for your current position, the system will prompt you to increase leverage or add margin.


# Margin Modes

AFX supports two margin modes: **Cross Margin** and **Isolated Margin**. The margin mode is configured per trading pair and can be switched even when positions or orders are open.

## Cross Margin

In Cross Margin mode, the entire available balance in your account is shared across all cross-margin positions. This provides more flexibility and reduces the risk of individual position liquidation, but a liquidation event will affect your entire account.

**Key characteristics:**

* Margin is shared across all cross-margin positions for the same settlement currency.
* Unrealized profit from one position can offset unrealized loss in another.
* Unrealized profit can be used to open new positions (both cross and isolated).
* Unrealized profit **cannot** be withdrawn or transferred.
* Cross margin is the **default** mode.

**Available Balance (Cross):**

```
Available = Balance - In Order & Position + Cross Unrealized PNL
```

## Isolated Margin

In Isolated Margin mode, margin is allocated individually to each position. If a position is liquidated, only the margin assigned to that specific position is at risk — your remaining account balance is protected.

**Key characteristics:**

* Each position has its own dedicated margin.
* You can manually add or remove margin for an isolated position.
* Unrealized profit only affects the current position.
* Unrealized profit **cannot** be used for other positions or orders.

**Available Balance (Isolated):**

```
Available = Balance - In Order & Position + Cross Unrealized PNL * α
```

Where `α` is the unrealized PNL liquidity coefficient, configured per trading pair based on asset liquidity. For example, BTC has `α = 0.98`, ETH has `α = 0.90`.

## Switching Margin Modes

You can switch between Cross and Isolated margin on a per-pair basis at any time, including when you have open positions. When switching from Cross to Isolated on an existing position, the system will calculate and allocate the appropriate initial margin.


# Position Modes

AFX supports two position modes: **One-Way Mode** and **Hedge Mode** (Two-Way). The position mode setting applies globally to all USDC-margined perpetual contracts.

## One-Way Mode

In One-Way mode, you can hold either a long **or** a short position on a given contract — not both simultaneously. Orders specify a size and direction only; there is no distinction between "open" and "close."

* Submitting an order in the opposite direction of your current position will reduce or close the existing position, and may open a reverse position if the order size exceeds the current position size.
* **Reduce Only** orders are available in this mode, ensuring that an order will only decrease your current position without opening a reverse position.

## Hedge Mode

In Hedge Mode (Two-Way), you can hold both a long and a short position on the same contract simultaneously where the mode is available. The order panel provides separate "Open" and "Close" tabs.

* Long and short positions are managed independently, each with their own entry price and margin.
* In Hedge Mode with Cross Margin, both positions share the account equity for liquidation purposes, but the liquidation price is calculated considering the net exposure.
* Position mode **cannot** be changed while you have any open positions or active orders (including conditional orders). You must close all positions and cancel all orders first.


# Order Types

AFX supports multiple order types to accommodate different trading strategies.

## Market Order

A Market Order executes immediately at the best available price in the order book.

* **Size** can be specified in the base currency (e.g., BTC) or in USDC.
* A **slippage tolerance** is applied to protect against unfavorable price movements. The default slippage is 3% (configurable from 0.5% to 5% per trading pair).
* The execution price is bounded by: Long — `Last Price * (1 + slippage)`, Short — `Last Price * (1 - slippage)`. Any portion of the order beyond the slippage boundary is cancelled.
* Market orders support attaching **Take Profit / Stop Loss** triggers.

## Limit Order

A Limit Order is placed at a specific price and will only execute at that price or better.

* **Price range:** 10% of Mark Price to 999,999.
* Supports quick-fill from the last traded price.
* **Time-in-force** options:
  * **GTC** (Good-Til-Cancelled) — The order remains active until fully filled or manually cancelled. This is the default.
  * **IOC** (Immediate-Or-Cancel) — Any unfilled portion is immediately cancelled.
  * **FOK** (Fill-Or-Kill) — The order must be filled entirely or it is cancelled completely.
  * **Post-Only** — The order will only be placed as a maker order. If it would immediately match, it is rejected instead.
* Limit orders support **Take Profit / Stop Loss** and **Reduce Only** options.

## Conditional Market Order (Stop Market)

A Conditional Market Order becomes a Market Order when the trigger price is reached.

* **Trigger Price** can be based on **Last Price** or **Mark Price**.
* Price range: 10% of Mark Price to 999,999.
* No margin cost check at the time of placement — the check occurs when the order is triggered.
* Supports **Reduce Only**.

## Conditional Limit Order (Stop Limit)

A Conditional Limit Order becomes a Limit Order when the trigger price is reached.

* Both a **Trigger Price** and a **Limit Price** are required.
* Trigger price can be based on **Last Price** or **Mark Price**.
* No margin cost check at the time of placement.
* Supports all time-in-force options available for Limit Orders.
* Supports **Reduce Only**.

## TWAP Order

TWAP (Time-Weighted Average Price) execution splits a large order into smaller sub-orders over a specified time period to reduce market impact. Availability may vary by market, account state, and product rollout stage.

## Reduce Only

Reduce Only is a special order attribute (available in One-Way mode) that ensures the order will only reduce an existing position — it will never open a new position or increase exposure in the opposite direction.

* If you are long, a Reduce Only sell order will only reduce or close your long position.
* If you are short, a Reduce Only buy order will only reduce or close your short position.
* If there is no open position, the Reduce Only order is rejected.
* If the position is closed before the Reduce Only order executes, the order is automatically cancelled.

## Order Limits

| Parameter                     | Limit |
| ----------------------------- | ----- |
| Active orders per symbol      | 200   |
| Conditional orders per symbol | 100   |


# Order Matching

AFX uses a central limit order book (CLOB) matching engine with on-chain verifiable settlement.

## Matching Rules

Orders are matched using **price-time priority**:

1. **Price priority** — The best priced orders are matched first. Buy orders at higher prices and sell orders at lower prices have priority.
2. **Time priority** — Among orders at the same price, earlier orders are matched first.

When a buy price ≥ sell price, the orders are matched. The trade executes at the **maker's price** (the price of the resting order in the book).

## Last Traded Price

The Last Price is determined by the first trade in the order book — the intersection of the highest buy price and the lowest sell price.

## Self-Trade Prevention (STP)

AFX implements platform-level self-trade prevention. Self-trades are detected and blocked automatically.

**Detection criteria:**

* Both orders originate from the same user's contract address.
* A new taker order enters at a price that would match against the user's own resting maker order.

**Handling:** Cancel Newest — The incoming taker order is rejected (not matched) if it would result in a self-trade. The existing maker order in the book remains unchanged. This approach maintains order book stability and is compatible with on-chain verification.


# Slippage

AFX provides configurable slippage protection for Market Orders to safeguard traders against unfavorable price movements due to low liquidity or volatile market conditions.

## How It Works

Slippage tolerance defines the maximum deviation from the current last traded price at which a Market Order can execute. Any portion of the order that would fill beyond the slippage boundary is automatically cancelled.

**Execution price boundaries:**

* Long / Buy: Execution Price ≤ Last Price × (1 + Slippage %)
* Short / Sell: Execution Price ≥ Last Price × (1 - Slippage %)

## Configuration

* Slippage is configured **per trading pair**, not globally.
* Configurable range: **0.5% to 5%** (in 0.1% increments).
* Default value: **3%**.

## Important Notes

* Slippage protection applies to **opening** positions only. Closing positions (including liquidation orders) are **not** subject to slippage limits, ensuring positions can always be fully closed.
* If the order book depth is insufficient to fill the order within the slippage boundary, only the portion within the boundary will be executed. The remaining portion is cancelled (partial fill behavior).


# Take profit and stop loss (TP/SL)

AFX provides flexible Take Profit (TP) and Stop Loss (SL) options that can be set when placing an order or added to an existing position.

## Setting TP/SL on Orders

When placing a Market or Limit order, you can attach TP and SL triggers. The default mode is **Entire Position** — the TP/SL applies to your full position for that symbol. The trigger price type defaults to **Last Price**.

TP/SL can be defined using four methods:

### 1. Trigger Price

Set a specific price at which the TP or SL should trigger. The system displays which direction (Long/Short) the TP/SL applies to and the estimated PNL.

### 2. Price Change (%)

Define the TP/SL as a percentage change from the estimated entry price.

* Long TP: Trigger Price = Entry Price × (1 + change%)
* Long SL: Trigger Price = Entry Price × (1 - change%)
* Short TP: Trigger Price = Entry Price × (1 - change%)
* Short SL: Trigger Price = Entry Price × (1 + change%)

### 3. ROI (%)

Define the TP/SL based on the return on investment, which factors in leverage.

* Long TP: Trigger Price = Entry Price × (1 + ROI% / Leverage)
* Long SL: Trigger Price = Entry Price × (1 - ROI% / Leverage)
* Short TP: Trigger Price = Entry Price × (1 - ROI% / Leverage)
* Short SL: Trigger Price = Entry Price × (1 + ROI% / Leverage)

### 4. PNL (USDC)

Set the TP/SL based on a specific profit or loss amount in USDC.

* Long: Trigger Price = PNL / Order Size + Entry Price
* Short: Trigger Price = Entry Price - PNL / Order Size

## Setting TP/SL on Positions

You can add or modify TP/SL on an existing position from the position panel. When setting TP/SL on a position:

* You can choose **Entire Position** mode or specify a custom size (**Partial** mode).
* Trigger price type supports both **Last Price** and **Mark Price**.
* The system displays estimated PNL based on the trigger price and current position parameters.

## TP/SL Behavior in One-Way Mode

In One-Way mode, TP/SL interactions follow specific rules when new orders are placed:

* **Adding to a position (same direction):** Existing TP/SL is preserved. If the new order also has TP/SL, the new settings override the existing ones.
* **Closing/reversing a position (opposite direction):** If the existing position has TP/SL, those TP/SL orders are automatically cancelled when the position is closed.
* **Partial close:** Existing TP/SL remains active and applies to the remaining position.

## Execution

When a TP/SL is triggered, it submits a **Market Order** to close the position (or the configured portion). Standard slippage protection applies.


# Risk Limits

AFX employs a tiered risk limit system that adjusts the maximum available leverage and maintenance margin rate (MMR) based on position size. As your position grows larger, the maximum leverage decreases and the maintenance margin requirement increases.

## How It Works

Each trading pair is assigned to a margin table. The table determines the leverage tiers and base MMR for that pair. Query live product metadata to map a market to its current `marginTableId`:

```
GET /info/public/product-meta
```

When a position's notional value crosses into a higher tier, the **entire position** is subject to the new tier's maximum leverage. If the current leverage exceeds the new tier's maximum, you will need to reduce leverage or close part of the position.

## Margin Table 1

Applies to: Not yet

| Position Notional (USDC) | Max Leverage | MMR   |
| ------------------------ | ------------ | ----- |
| 0 – 20,000,000           | 40x          | 1.25% |
| > 20,000,000             | 20x          | 1.25% |

## Margin Table 2

Example markets: XAUUSDC, CLUSDC, SOLUSDC, XRPUSDC

| Position Notional (USDC) | Max Leverage | MMR |
| ------------------------ | ------------ | --- |
| 0 – 2,000,000            | 25x          | 2%  |
| 2,000,000 – 5,000,000    | 20x          | 2%  |
| > 5,000,000              | 10x          | 2%  |

## Margin Table 3

Example markets: ZECUSDC, ONDOUSDC

| Position Notional (USDC) | Max Leverage | MMR  |
| ------------------------ | ------------ | ---- |
| 0 – 1,000,000            | 20x          | 2.5% |
| > 1,000,000              | 10x          | 2.5% |

## Margin Table 4

Example markets: equity, ETF, and other lower-leverage markets

| Position Notional (USDC) | Max Leverage | MMR |
| ------------------------ | ------------ | --- |
| 0 – 50,000               | 10x          | 5%  |
| > 50,000                 | 5x           | 5%  |

## Margin Table 5

Example markets: BTCUSDC, ETHUSDC

| Position Notional (USDC) | Max Leverage | MMR  |
| ------------------------ | ------------ | ---- |
| 0 – 1,000,000            | 100x         | 0.5% |
| 1,000,000 - 2,000,000    | 60x          | 0.5% |
| 2,000,000 - 20,000,000   | 40x          | 0.5% |
| > 20,000,000             | 20x          | 0.5% |

## Maintenance Margin Rate

The Maintenance Margin Rate (MMR) is the minimum margin percentage required to keep a position open. For the lowest tier of each type, the base MMR is shown in the table. Higher tiers have a proportionally higher effective MMR, calculated as:

```
Effective MMR = 1 / (2 × Max Leverage)
```

When the margin ratio (Maintenance Margin / Position Equity) reaches 100%, the position is liquidated. See [Liquidation](/trading-rules/liquidation) for details.


# Liquidation

When a trader's margin ratio reaches 100%, the system initiates liquidation to prevent further losses. AFX employs a multi-layered liquidation system designed to minimize the impact on traders while maintaining platform solvency.

## Liquidation Trigger

Liquidation is triggered when:

```
Margin Ratio = Maintenance Margin (MM) / Position Equity = 100%
```

The trigger condition is the same for both Cross and Isolated margin modes, but the Equity calculation differs:

**Isolated Margin:**

```
Position Equity = Position Margin + Isolated Unrealized PNL
              = Initial Margin + Close Fee + Added Margin + Isolated Unrealized PNL
```

**Cross Margin:**

```
Position Equity = Wallet Balance + Cross Unrealized PNL - Isolated Balance (IB)
```

Where IB = total margin locked in isolated positions.

## Margin Ratio Alerts

For users registered with email, the system sends warning notifications at the following thresholds:

| Margin Ratio | Alert                                            |
| ------------ | ------------------------------------------------ |
| 50%          | First warning — add margin recommended           |
| 67%          | Second warning — add margin urgently recommended |
| 100%         | Liquidation triggered                            |

## Liquidation Process

See [Liquidation Process](/trading-rules/liquidation-process) for the detailed multi-phase liquidation flow.

## Auto-Deleveraging (ADL)

In extreme market conditions where normal liquidation cannot fully close a position, the Auto-Deleveraging system is activated. See [ADL](/trading-rules/adl) for details.

## Estimated Liquidation Price

The estimated liquidation price is displayed on the trading interface for reference. The formulas are:

**Long position:**

```
Liq. Price = (1 - 1/L) × 1/(1 - MMR - feeRate) × Entry Price
```

**Short position:**

```
Liq. Price = (1 + 1/L) × 1/(1 + MMR + feeRate) × Entry Price
```

Where:

* **L** = Effective leverage = Position Value / Equity
* **MMR** = Maintenance Margin Rate (see [Risk Limits](/trading-rules/risk-limits))
* **feeRate** = Taker fee rate

The estimated liquidation price is rounded to the tick size (up for longs, down for shorts) and is for reference only — actual liquidation depends on the real-time margin ratio reaching 100%.


# Liquidation Process

AFX uses a multi-phase liquidation process to handle under-margined positions in an orderly manner, minimizing market impact and protecting other users.

## Phase 1: Trigger and Pre-Processing

When the Risk Engine detects that a position's margin ratio has reached 100%:

1. The account is flagged as "in liquidation."
2. All open orders in the **same direction** as the endangered position are cancelled. If cancelling these orders brings the margin ratio back below 95%, the liquidation stops.
3. If the margin ratio is still above the safe threshold after cancellation, the system proceeds to forcibly close the position.

**Tiered Liquidation:** For positions with a notional value exceeding 100,000 USDC, the system liquidates in steps — closing 20% of the position at a time, with a 30-second cooldown between each step. If the margin ratio recovers to the safe level after any step, the liquidation process stops.

The position is closed at market price. Any remaining margin after closing is returned to the user's account.

## Phase 2: Vault Takeover

If the liquidated position cannot be immediately closed in the market (e.g., due to insufficient liquidity), the **LP Vault** takes over the position.

1. The Vault calculates the notional value of the position using the Mark Price.
2. The positions taken over cannot exceed the Vault's limit; otherwise, ADL will be triggered directly.
3. The Vault collects a **liquidation fee** of 0.5% of the remaining maintenance margin from the liquidated position.

## Phase 3: Market Matching

1. The Vault's liquidation orders enter the matching engine.
2. Other market participants (market makers, regular traders) can take the other side of these orders.
3. Once filled, the Vault recovers the position margin and any remaining balance.

## Phase 4: ADL (if Vault is Overwhelmed)

If the Vault cannot fully close the position at a reasonable price (market depth is insufficient) or the Vault's balance becomes negative, the system triggers Auto-Deleveraging. See [ADL](/trading-rules/adl) for details.

## Fund Flow Summary

| Participant           | Outcome                                                                                                      |
| --------------------- | ------------------------------------------------------------------------------------------------------------ |
| Liquidated user       | Position closed; remaining margin (minus liquidation fee) returned. If fully depleted, balance goes to zero. |
| LP Vault              | Receives liquidation fee. Assumes temporary position risk during takeover.                                   |
| Market counterparties | Can fill liquidation orders at a discount.                                                                   |
| ADL targets           | Positions partially or fully reduced at the Vault's liquidation price (only in extreme cases).               |


# ADL

Auto-Deleveraging is the last line of defense in AFX's risk management system. Under extreme market conditions, when normal liquidation processes cannot fully close out positions and the LP Vault cannot absorb the remaining risk, the system activates ADL to reduce counterparty profitable positions and restore the platform's overall solvency.

## How It Works

When the system determines that conventional measures can no longer cover the risk exposure, ADL automatically selects traders holding opposite-direction positions for deleveraging. The system considers multiple factors to determine priority — generally, positions with higher profits and higher leverage are selected first.

Deleveraged traders receive the corresponding realized PNL.

## How to Reduce ADL Risk

* **Lower your effective leverage** — add margin or reduce position size
* **Take profits when appropriate** — realizing partial gains lowers your priority

## Key Notes

* ADL events are extremely rare, triggered only as a last resort under extreme market conditions
* ADL is a backstop mechanism designed to protect the funds of all users
* The system exhausts all regular liquidation and Vault takeover options before resorting to ADL


# Oracle Price

The Index Price (also called the Oracle Price) represents the fair spot market price of an asset. It is derived from multiple major centralized exchanges and serves as the foundation for the funding rate calculation and as a reference for the Mark Price.

## Data Sources

Each trading pair has a configured set of exchange price sources with assigned weights. For most assets, the default sources and weights are:

| Exchange | Weight |
| -------- | ------ |
| Binance  | 70%    |
| Bybit    | 20%    |
| OKX      | 10%    |

The Oracle Price is published every 3 seconds by the validator node.

```
Oracle Price = Σ (Price_i × Weight_i)
```

For the full list of data sources per trading pair, see [Supported Assets](/trading-rules/supported-assets).

## Protection Mechanisms

Several safeguards ensure the Oracle Price remains accurate and resistant to manipulation:

{% stepper %}
{% step %}

#### Timeout Detection

If an exchange's price feed has not been updated for more than **15 minutes** (configurable per pair via `MaxDelay`), that exchange is excluded from the Oracle Price calculation. Once the feed recovers, it is automatically re-included.
{% endstep %}

{% step %}

#### Outlier Filtering

If an exchange's reported price deviates from the median by more than the configured threshold (e.g., ±5% for most assets; ±1% for BTC and ETH), the price is automatically capped to the deviation threshold. Once the price returns to a normal range, it is re-included at its actual value.

**Example:** If the median spot price is 100 and OKX reports 120 (a 20% deviation exceeding the 5% cap), OKX's price is capped to 105 for the calculation.
{% endstep %}

{% step %}

#### Smoothing Mechanism

To prevent sudden price jumps, the Oracle Price limits the maximum per-update change. For example, with a 0.5% cap per update, if the previous Oracle Price was 99.8, the next Oracle Price is bounded to \[99.3, 100.3].
{% endstep %}

{% step %}

#### Dynamic Weighting

Exchange weights are dynamically adjusted based on two factors:

* **Liquidity Weight W(L):** Reflects the exchange's trading depth and volume. Measured using the square root of the exchange's 1-minute trading volume, preventing any single exchange from having disproportionate influence.
* **Latency Weight W(T):** Reflects how quickly the exchange's price data is received. Calculated using an exponential decay function: `W(T) = e^(-k × Latency)` where k = 0.5. Lower latency results in higher weight.

The final weight for each exchange is proportional to `W(L) × W(T)`, normalized so all weights sum to 100%.
{% endstep %}
{% endstepper %}


# Mark Price

The Mark Price is used to calculate unrealized PNL, margin requirements, liquidation triggers, and conditional order activations. It is designed to be resistant to price manipulation by incorporating multiple data sources.

## Calculation

The Mark Price is updated approximately every 3 seconds, in sync with the oracle price feed. It is determined as the **median** of three price components:

1. **Price 1** = Oracle Price + 2.5-minute Moving Average of (Mid Price - Oracle Price)
2. **Price 2** = Mid(Ask1, Bid1, Last Price)
3. **Price 3** = Weighted median of perpetual contract mid-prices from five major exchanges (Binance, OKX, Bybit, Gate, MEXC) with weights 3:2:2:1:1

If only two of the three components are available, a fourth input is added: the 30-second moving average of Mid(Ask1, Bid1, Last Price).

```
Mark Price = Median(Price 1, Price 2, Price 3)
```

Where:

* **Oracle Price** is the weighted-average spot price from external exchanges (see [Oracle Price](/trading-rules/oracle-price)).
* **Mid Price** = (Ask1 + Bid1) / 2 on AFX's own order book.
* **Last Price** = Most recent trade price on AFX.

## Why Mark Price Matters

The Mark Price is distinct from the Last Price. While the Last Price reflects the most recent trade, the Mark Price provides a more stable and manipulation-resistant reference. It is used for:

* Calculating unrealized PNL and margin ratios.
* Determining liquidation triggers.
* Computing estimated liquidation prices shown in the UI.
* Triggering conditional orders (when set to Mark Price trigger type).

## During Listing

For newly listed contracts, during the initial risk-control period (first 15 minutes after trading begins), the Mark Price equals the Oracle Price. After this period, the Mark Price switches to the standard calculation described above.


# Funding Rate

Funding rates are periodic payments exchanged between long and short position holders. They serve to keep the perpetual contract price anchored to the underlying spot price.

## Overview

* When the funding rate is **positive**, long positions pay short positions.
* When the funding rate is **negative**, short positions pay long positions.
* Funding is settled automatically — no action is required from the trader.

## Funding Interval

The default funding interval for most trading pairs is **4 hours** (every 4 hours), with settlement occurring at fixed intervals. Some assets may use a different interval (e.g., 1 hour for certain pairs). See [Supported Assets](/trading-rules/supported-assets) for per-pair details.

## Funding Rate Formula

The funding rate consists of two components: the **Interest Rate** and the **Premium Index**.

```
Funding Rate (F) = { Average Premium Index (P) + clamp[ Interest Rate (I) - Average Premium Index (P), 0.05%, -0.05% ] } / (8 / N)
```

Where:

* **I** (Interest Rate) = 0.01% (fixed, regardless of the funding interval).
* **N** = Funding interval in hours (e.g., 4 for a 4-hour interval, 1 for a 1-hour interval).
* **P** = Time-weighted Average Premium Index over the funding period.

### Funding Rate Cap

The funding rate is capped at **±2%** per interval for most crypto assets and **±0.375%** for commodity pairs (XAU, XAG).

## Premium Index

The Premium Index measures the deviation of the perpetual contract price from the Oracle Price.

```
Premium Index = [ Max(0, Impact Bid Price - Oracle Price) - Max(0, Oracle Price - Impact Ask Price) ] / Oracle Price
```

Where:

* **Impact Bid Price** = The average execution price to sell the "Impact Value" notional on the bid side of the order book.
* **Impact Ask Price** = The average execution price to buy the "Impact Value" notional on the ask side of the order book.
* **Impact Value** = 200 × Max Leverage for the pair (currently 20,000 USDC for most pairs).

### Time-Weighted Average

The Premium Index is sampled every 5 seconds. The Average Premium Index is computed as a time-weighted average where more recent samples carry greater weight:

```
Average Premium Index (P) = (P_1 × 1 + P_2 × 2 + ... + P_n × n) / (1 + 2 + ... + n)
```

For a 1-hour interval with 5-second sampling, n = 720. For a 4-hour interval, n = 2,880.

## Funding Fee Calculation

```
Funding Fee = Oracle Price × Position Size × Funding Rate
```

The funding fee is calculated at each settlement time based on your position size and the Oracle Price at that moment. Funding fees are automatically debited from or credited to your account balance.

## Example

Assume you hold a 1 BTC long position with Oracle Price at 100,000 USDC and the funding rate is +0.01%:

```
Funding Fee = 100,000 × 1 × 0.0001 = 10 USDC
```

Since the rate is positive and you are long, you pay 10 USDC. This amount is distributed to short position holders.


# Vaults

AFX Vaults allow users to participate in the platform's liquidity and trading strategies. There are two types of Vaults: the **LP Vault (ALP)**, which is the platform's core liquidity vault, and **User Vaults**, which are community-created strategy vaults.

## Vault Types

### LP Vault (ALP)

The LP Vault is the protocol-level vault that provides liquidity to the AFX exchange. It handles market making, liquidation takeovers, and earns fees from platform trading activity. There is no management fee (Operator Fee = 0%). Any user can deposit USDC into the LP Vault to share in its returns.

See [LP Vault (ALP)](/vaults/lp-vault) for details.

### User Vaults

User Vaults are created by individual traders who want to manage funds on behalf of depositors. Vault creators (leaders) execute trading strategies using the pooled funds and earn a **10% profit share** on depositors' gains. Availability and creation requirements may vary by rollout stage and account eligibility.

## Key Concepts

### NAV (Net Asset Value per Share)

All Vaults use a share-based (NAV) accounting system:

* When you deposit, you receive shares at the current NAV price.
* As the Vault's total assets grow (through trading profits), the NAV increases.
* When you withdraw, your shares are redeemed at the current NAV.

This ensures that each depositor's return corresponds to the actual performance during their holding period.

### Vault Isolation

Each Vault operates with a separate trading account, completely isolated from the creator's personal trading account and from other Vaults. Depositing into or trading within a Vault does not affect any other accounts.

## Roles

| Role                     | Permissions                                                                                                 |
| ------------------------ | ----------------------------------------------------------------------------------------------------------- |
| **Depositor**            | Deposit USDC, withdraw USDC, view Vault performance and positions.                                          |
| **Vault Leader**         | All depositor permissions, plus: execute trades, manage positions, adjust risk parameters, close the Vault. |
| **Vault Smart Contract** | Holds deposited assets, mints/burns shares, calculates NAV, distributes profits.                            |


# LP Vault

The LP Vault — also known as **AFX Provider (ALP)** — is the protocol-level liquidity vault. It serves as the backbone of the AFX exchange, providing liquidity for trading, handling liquidation takeovers, and absorbing market-making risk.

## Overview

* **Operator Fee:** 0% (no management fee)
* **Profit Share:** 0% (all returns go to depositors)
* **Deposit Currency:** USDC
* **Lock Period:** Deposits are locked for **4 days** before becoming withdrawable.

## How It Works

The LP Vault consists of multiple sub-vaults, each serving a specific function:

* **Market Making Sub-Vaults:** Execute market-making strategies to provide liquidity on the order book and earn the bid-ask spread.
* **Liquidation Takeover Sub-Vaults:** Absorb positions from liquidated users and close them at a discount, earning the liquidation fee and any favorable price difference.

A strategy smart contract manages the trading signals and returns for each sub-vault. The Vault manager (protocol team) configures strategy allocation and risk parameters but cannot directly withdraw user funds.

## Revenue Sources

1. **Trading fees:** After deducting the **Referral commission** from the AFX-wide fee revenue, 50% of the remaining amount will be transferred to the LP Vault as earnings.
2. **Liquidation takeover margin:** Remaining maintenance margin from liquidated positions.
3. **Liquidation fees:** 0.5% of the maintenance margin collected during position takeover.
4. **Strategy earnings:** The LP Vault will be managed by professional traders who implement trading strategies. Any profits generated will also remain within the LP Vault.

## NAV Calculation

Since the LP Vault has multiple sub-vaults with different performance, the main Vault NAV is a **weighted average** of each sub-vault's NAV:

```
Main Vault NAV = Σ (Sub-Vault NAV_i × Weight_i)
```

For example, if Sub-Vault 1 has NAV = 1.1 (weight 40%), Sub-Vault 2 has NAV = 1.2 (weight 30%), Sub-Vault 3 has NAV = 1.4 (weight 20%), and Sub-Vault 4 has NAV = 1.3 (weight 10%), then:

```
Main Vault NAV = 1.1 × 40% + 1.2 × 30% + 1.4 × 20% + 1.3 × 10% = 1.21
```

## Deposits

* Minimum deposit: No minimum beyond what is required by the blockchain transaction.
* No maximum deposit limit.
* Deposits are locked for **4 days** before they can be withdrawn.
* Shares are minted at the current NAV at the time of deposit.

## Withdrawals

All withdrawals are processed from the main Vault. If the main Vault has sufficient available balance, the withdrawal is processed immediately. If not, sub-vaults contribute funds proportionally based on their configured ratios.

Each sub-vault reserves **20% of min(Balance, Available Balance)** as a liquidity buffer. If sub-vault funds are still insufficient after using the buffer, the system may cancel orders or close positions (starting from smallest margin) to free up capital.


# User Vaults

User Vaults allow any trader to create and manage a strategy vault on AFX. Depositors allocate capital to a Vault leader's trading strategies, and the leader earns a profit share on depositors' gains.

## Creating a Vault

{% stepper %}
{% step %}

### Connect your wallet and open Vaults

Connect your wallet and navigate to the Vaults page.
{% endstep %}

{% step %}

### Create the vault

Click **Create Vault** and fill in the required fields:

* **Vault Name** (permanent, cannot be changed)
* **Vault Description** (permanent, cannot be changed)
* **Initial Deposit:** Minimum 100 USDC
  {% endstep %}

{% step %}

### Pay the creation fee

Pay the **100 USDC creation fee** (non-refundable, even if you later close the Vault).
{% endstep %}
{% endstepper %}

**Limits:** Each wallet can create up to **5 User Vaults**.

## Profit Share

User Vault leaders receive a **10% profit share** on depositors' gains at the time of withdrawal. The profit share is calculated as follows:

{% stepper %}
{% step %}

### Track average cost basis

The system tracks each depositor's average cost basis (total invested / total shares).
{% endstep %}

{% step %}

### Calculate gross profit

When a depositor withdraws, the system calculates their gross profit: Withdrawal Amount - (Shares Withdrawn × Average Cost).
{% endstep %}

{% step %}

### Deduct profit share if profit is positive

If the gross profit is positive, 10% is deducted as the leader's profit share.
{% endstep %}

{% step %}

### Send the net withdrawal amount

The net withdrawal amount is sent to the depositor's wallet; the profit share increases the leader's share balance.
{% endstep %}
{% endstepper %}

**Example:** A depositor invested $111 total for 110 shares (avg cost $1.0091/share). They withdraw 50 shares at NAV $1.21:

* Withdrawal = 50 × $1.21 = $60.50
* Cost = 50 × $1.0091 = $50.455
* Gross Profit = $60.50 - $50.455 = $10.045
* Profit Share (10%) = $1.0045 (transferred to leader)
* Depositor Receives = $60.50 - $1.0045 = $59.4955

## Leader Requirements

The Vault leader must maintain a **minimum of 5% of total vault shares** (and at least 100 USDC in value). If the leader's share drops below 5%, the following restrictions apply:

* Cannot withdraw funds
* Cannot increase position sizes (reducing/closing positions is still allowed)
* Cannot withdraw profit share
* Can still deposit additional funds

This requirement ensures the leader has meaningful skin in the game.

## Vault Operations

Leaders have access to a **Creator Operations** panel with the following controls:

* **Close Vault:** Initiates a 48-hour cooldown period. All open positions must be closed before initiating closure. During the cooldown, depositors can freely withdraw. After the cooldown, remaining funds are distributed proportionally by shares.
* **Trade for Vault:** Opens the trading interface in Vault context, where all trades are executed using the Vault's funds.
* **Disable Deposits:** Toggle to prevent new deposits from other users.
* **Enable Auto-Close on Withdrawal:** When enabled, if available balance is insufficient for a withdrawal, the system automatically closes positions to free up funds. When disabled, withdrawals that exceed available balance will simply fail.

## Deposits and Withdrawals

**Deposits:**

* No maximum deposit limit.
* Shares are minted at the current NAV.
* The initial 100 USDC creation deposit is usable as trading capital.

**Withdrawals:**

* Withdrawals are processed based on the current NAV.
* If the Vault has sufficient available balance, withdrawals are instant.
* NAV is updated in real-time. Funds are only transferred when the depositor initiates a withdrawal.

## Settlement

* NAV is calculated in real-time based on the Vault's total assets (balance + unrealized PNL).
* There is no periodic settlement — profits accumulate continuously in the NAV.
* Funds are only transferred to the depositor's wallet when they explicitly withdraw.

## Closing a Vault

When a leader closes a Vault:

{% stepper %}
{% step %}

### Close all positions

All positions must be fully closed (no open positions or orders).
{% endstep %}

{% step %}

### Start the cooldown

A 48-hour cooldown period begins.
{% endstep %}

{% step %}

### Restrict new activity

During the cooldown, no new deposits or new positions are allowed.
{% endstep %}

{% step %}

### Allow withdrawals

Depositors can withdraw freely during the cooldown.
{% endstep %}

{% step %}

### Distribute remaining funds

After the cooldown, remaining funds are distributed to all depositors proportionally by share count, with the 100 USDC creation fee deducted (or as much as remains if the balance is less than 100 USDC).
{% endstep %}
{% endstepper %}


# Affiliate Program

### 1. What is the Referral Commission Program

The Referral Commission Program is a long-term incentive plan open to all eligible traders. Generate your unique referral link, invite friends to trade, and earn **ongoing commissions on your direct invitees' trading fees**, plus a **sub-agent override on your downline network**. The more they trade and the wider your network grows, the more you earn.

### 2. Two Core Benefits

#### 2.1 Direct Commission — Earn on Every Trade Your Invitees Make

* **Binding**: A user becomes permanently bound to you the first time they connect a wallet via your unique link (<https://app.afx.xyz/?referral=`[your_code]`>).
* **Commission rule**: For every trading fee paid by your invitee, you receive a rebate based on **your commission rate**.
* **Commission rate metric**: Your rate is determined by the **total cumulative trading volume of your entire downline network (all tiers)** and is **auto-updated daily at UTC 00:00**. The more active your network, the higher your rate.

**Commission Rate Tier Schedule:**

| Cumulative Volume | Commission Rate |
| ----------------- | --------------: |
| ≥ $0              |             10% |
| ≥ $50,000,000     |             15% |
| ≥ $75,000,000     |             20% |
| ≥ $100,000,000    |             25% |
| ≥ $200,000,000    |             30% |
| ≥ $500,000,000    |             35% |

> Volumes are denominated in USDC and refer to the cumulative trading volume of your entire downline network.

#### 2.2 Sub-Agent Override — Fixed 5%, Always Stackable

In addition to direct commissions, you automatically earn a **5% override** on the trading fees of **second-tier users invited by your direct invitees**.

**Relationship illustration:**

> Suppose the referral chain is A → B → C → D → E

| Fee Source     | Direct Commission (by upline rate) | Sub-Agent Override (fixed 5%) |
| -------------- | ---------------------------------- | ----------------------------- |
| Generated by B | A                                  | —                             |
| Generated by C | B (at B's rate)                    | A (5%)                        |
| Generated by D | C (at C's rate)                    | B (5%)                        |
| Generated by E | D (at D's rate)                    | C (5%)                        |

**Formula:**

```
Your reward this period
= Σ (Direct invitee fees × Your commission rate)
+ Σ (Second-tier user fees × 5%)
```

**Example:**

> Suppose C generates 100 USDC in trading fees today, and B's commission rate is 35%:
>
> * B's direct commission = 100 × 35% = **35 USDC**
> * A's sub-agent override = 100 × 5% = **5 USDC**

### 3. Eligibility & Binding Rules

| Item                   | Rule                                                                                                           |
| ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| Generate referral code | Reach **10,000 USDC** in personal cumulative trading volume to automatically receive your unique referral code |
| New user binding       | Connecting a wallet via your link automatically establishes a permanent binding                                |
| Existing user binding  | May manually bind to an upline **once**; cannot be changed afterwards                                          |

### 4. Settlement & Payout

* **Settlement time**: settled automatically at **UTC 00:00 daily**.
* **Payout method**: commissions are sent directly to your wallet address — **no manual claim required**.
* **Settlement currency**: USDC.

### 5. Why Join the Referral Program

* ✅ **Lifetime earnings**: every trade by your invitees brings you income — no expiration.
* ✅ **Multi-tier stacking**: direct commission + 5% sub-agent override means your second-tier network earns for you too.
* ✅ **Auto-settled**: rewards are paid out automatically at UTC 00:00 every day — **zero effort**.
* ✅ **Rate grows with you**: the larger your downline's volume, the higher your commission rate — a positive feedback loop.

### 6. Notes

* **Two separate metrics — do not confuse them**:
  * **Commission rate upgrade** → based on your **entire downline network's cumulative trading volume**.
  * **Sub-agent override** → a fixed **5%** of your second-tier users' trading fees.
* The platform reserves the right to investigate and reverse rewards from wash trading, self-referrals, related-account cross-invitations, or any other abusive behavior.
* The platform reserves the right to interpret and adjust these rules. Final interpretation rights belong to the platform.


# VIP Program

#### 1. What is the VIP Program

The VIP Program is an exclusive benefits system for active traders. Once you become a VIP, you not only enjoy **lower trading fee rates**, but also **share in the platform's fee reward pool on an ongoing basis** — the more you trade, the more you earn.

#### 2. Two Core VIP Benefits

**2.1 Tiered Fee Rates — Higher Tier, Lower Cost**

* **Base rates**: Taker 0.06%, Maker 0.01%
* Both Taker and Maker rates decrease as your VIP tier rises, directly reducing your trading costs.
* **Tier qualification metric**: your VIP tier is determined by your **total trading volume over the past 30 days** (master account and all sub-accounts combined).

**VIP Tier & Fee Schedule:**

| VIP Tier | Min. 30-Day Trading Volume | Maker Fee Rate | Taker Fee Rate |
| -------- | -------------------------: | -------------: | -------------: |
| Non-VIP  |                          — |        0.0100% |        0.0600% |
| VIP 1    |                 $5,000,000 |        0.0080% |        0.0550% |
| VIP 2    |                $10,000,000 |        0.0060% |        0.0500% |
| VIP 3    |                $25,000,000 |        0.0040% |        0.0450% |
| VIP 4    |               $500,000,000 |        0.0020% |        0.0375% |
| VIP 5    |             $1,250,000,000 |        0.0010% |        0.0350% |

> Volume thresholds are denominated in USDC.

**2.2 Fee Reward Pool — Everyone Shares, More Trading = More Rewards**

The platform continuously channels **30%–50% of its trading-fee revenue** into the VIP **reward pool**, distributed back to VIP users. The exact ratio is **dynamically adjusted** in line with the platform's growth stage and business cycles, but a **substantial pay-back ratio is maintained over the long term**, ensuring that VIP users genuinely share in the platform's upside.

As long as you are at VIP1 or above, you are **automatically enrolled** in each distribution.

**Distribution metric**: rewards are allocated according to your **share of Taker volume over the past 30 days** among **all VIP users**.

**Distribution formula:**

```
Your reward this period
= Total fee reward pool this period
× (Your Taker volume over the past 30 days / Sum of Taker volume over the past 30 days across all VIP users)
```

**Example:**

> Suppose the reward pool for a given period is X, and the only VIP users on the platform are A and B:
>
> * User A's Taker volume in the past 30 days = 100
> * User B's Taker volume in the past 30 days = 900
> * Then A receives 10% × X, and B receives 90% × X.

In short, the larger your share of Taker volume within the VIP cohort, the bigger your share of the rewards.

#### 3. Why Become a VIP

* ✅ **Save on costs**: tiered fees mean higher tier = lower trading fees.
* ✅ **Earn rewards**: starting from VIP1, you automatically participate in the fee reward pool — **no sign-up needed**. The platform continuously channels **30%–50% of fee revenue** into the reward pool.
* ✅ **Compounding effect**: trade more → climb tiers → lower fees → larger share of rewards — a positive feedback loop.
* ✅ **Master + sub-account aggregation**: institutional and team users have all sub-account volumes consolidated under the master account, making it easier to reach higher tiers.

#### 4. Notes

* **Two separate metrics — do not confuse them**:
  * **VIP tier upgrade** → based on your **total trading volume over the past 30 days**.
  * **Fee reward distribution** → based on your **share of Taker volume over the past 30 days among all VIP users**.
* Both metrics **aggregate the master account and all sub-accounts**.
* VIP tiers and reward allocations are recalculated each period — please check your account dashboard for the latest status.
* The platform reserves the right to interpret and adjust these rules. Final interpretation rights belong to the platform.


# Points

### Overview

The AFX Mainnet Points Program is now officially live.This is AFX's most direct way of rewarding every genuine participant who contributes to the protocol’s success. Whether you are an active trader, a liquidity provider, or a Captain leading your guild — every contribution you make is recorded as points and converted into governance tokens at TGE.The program runs across three Seasons in sequence, each with its own dedicated points pool. All points from every Season accumulate together — nothing resets, nothing expires — and are redeemed at a unified rate at TGE. Testnet retroactive points will be included in the final calculation as well.

#### **Why participate?**

* Points convert directly into governance tokens, making this one of the most direct ways to earn the protocol's native token
* All three earning methods are independent and can be combined simultaneously — there is no cap on how many ways you can participate
* The earlier you participate, the longer you have to accumulate — giving you a larger potential share of each week's fixed points pool
* Governance token holders enjoy higher trading rewards, lower trading fees, higher referral commissions, and more

The specific points-to-token exchange rate and claim process will be announced before TGE.

***

1. ### How Points Are Distributed

A fixed number of points is released each week. Your share is determined by your contribution relative to other participants during that period.

* **Settlement cycle:** Every Monday at 00:00 UTC
* **Activity window:** Monday 00:00 UTC through Sunday 23:59 UTC
* **Distribution timing:** Points are calculated and released in the following week

> The weekly budget and scoring priorities may be adjusted across different phases of the program to match the protocol's evolving priorities. Changes will be announced in advance.

***

2. ### Season Structure

The Mainnet Points Program runs across three consecutive Seasons. Each Season has its own dedicated points pool, with the total size announced at the start of that Season.

All points accumulate across Seasons and are redeemed together at TGE — they do not reset or expire when a Season ends.Each Season features two independent pools and three ways to earn:

* **Trading + AFX LP Vault Combined Pool** — Trading and liquidity provision share a single pool, with the split between the two adjusted dynamically each week based on protocol conditions
* **Guild Pool** — Rewards Guild League participants, operating independently with no overlap with the trading or AFX LP Vault allocation

Full details on pool sizes and current ratios are available on each Season's dedicated page.

> The split between trading and AFX LP Vault points is adjusted dynamically each week based on actual protocol conditions — there is no fixed ratio. The current ratio will be announced before each weekly settlement.

***

3. ### How to Earn Points

There are three ways to earn points. All three can be combined simultaneously and do not affect each other.

#### 3.1 Trading

Active traders earn points based on multiple dimensions of their trading behavior. The system evaluates your overall contribution to the protocol, not simply trading volume. Relevant factors include:

* **Trade execution** — Actively taking and making orders in available markets
* **Position contribution** — Holding open positions over time, contributing to protocol open interest depth
* **Market diversity** — Trading across multiple pairs rather than concentrating on a single market

The relative weight of each factor may be adjusted over time to reflect the protocol's changing priorities.

#### 3.2 AFX LP Vault

Users who deposit funds into the AFX LP Vault earn points based on their actual contribution to protocol liquidity depth. Liquidity providers are essential to ensuring smooth trade execution for all users — they are a core pillar of the protocol's health.Trading points and AFX LP Vault points share the same combined pool, with the ratio between them adjusted dynamically each week. Providing liquidity does not reduce your trading points, and vice versa — both can be earned at the same time.

#### 3.3 Guild League

The Guild League is a team-based competition system designed to align the interests of community Captains with their members.**How it works:**

* Captains form guilds and invite members to join
* Guilds are ranked each week based on total trading volume
* The Top 50 guilds share the weekly prize pool across a five-tier structure, with all guilds in the same tier receiving equal allocation
* Rankings reset every week — last week's top guild has no guaranteed advantage, giving guilds of all sizes a real chance to compete
* If fewer than 50 guilds participate in a given week, any unallocated points roll into the discretionary pool

**Weekly prize pool tier structure:**

|  Tier  | Guilds | Share of Weekly Pool | Per Guild |
| :----: | :----: | :------------------: | :-------: |
| Tier 1 |    1   |          20%         |    20%    |
| Tier 2 |    3   |          20%         |  \~6.67%  |
| Tier 3 |    6   |          20%         |  \~3.33%  |
| Tier 4 |   10   |          20%         |     2%    |
| Tier 5 |   30   |          20%         |  \~0.67%  |

**Internal reward distribution:**&#x50;oints earned by each guild are split between the Captain and members as follows:

|  Tier  | Captain's Share | Members' Share |
| :----: | :-------------: | :------------: |
| Tier 1 |        9%       |       91%      |
| Tier 2 |        7%       |       93%      |
| Tier 3 |        6%       |       94%      |
| Tier 4 |        5%       |       95%      |
| Tier 5 |        6%       |       94%      |

The members' share is further distributed among individual members based on each person's trading contribution during that week.**Participation threshold:**

* Guilds must maintain a minimum number of genuinely active members to qualify for reward distribution
* A guild qualifies as active when it has at least **10 members** each generating at least **$1,000 in trading volume** during the week
* Inactive or placeholder accounts do not count toward the active member threshold
* The Guild League has its own independent points allocation, separate from the trading and AFX LP Vault pools

**How to join:** Find a Captain's guild invitation link in the AFX community.

***

4. ### Referral Commission Program

Earn additional commissions by inviting others to trade on AFX. Your commission rate is determined by the **cumulative trading volume of your entire referral network** — the more active your network, the higher your rate.

#### 4.1 Primary Commission Rate

| Network Cumulative Volume | Commission Rate |
| :-----------------------: | :-------------: |
|           >= $0           |       10%       |
|       >= $50,000,000      |       15%       |
|       >= $75,000,000      |       20%       |
|      >= $100,000,000      |       25%       |
|      >= $200,000,000      |       30%       |
|      >= $500,000,000      |       35%       |

#### 4.2 Bonus Commission

In addition to the primary commission, you can earn an additional fixed bonus from the next level of your referral network. The maximum combined commission rate is **40%**.

> Referral rewards are based on the genuine trading activity of referred users. Wash trading, self-referral, and coordinated manipulation will be detected by the anti-sybil system, and related points will be reduced or voided.

***

5. ### API Rules

To protect traders, the weekly trading points pool is divided into two **fully independent** sub-pools. Note that this split applies only to trading points — AFX LP Vault points are not affected by this mechanism.**Retail Pool** — For users trading manually via the web interface or mobile. These are manual traders and the protocol's core user group.**API Pool** — For users trading via API, including market makers, quantitative trading teams, and high-frequency traders.The two pools operate independently. No matter how much volume API users generate, it does not reduce the points available to manual traders.

* The API pool ratio is dynamically adjusted each week based on API users' actual contribution to total protocol volume
* A calibration mechanism ensures the API pool stays proportional to actual API contribution, while always prioritizing manual traders' interests
* The API pool has both a floor and a ceiling, preventing extreme misallocation in either direction
* Within the API pool, a single user has a daily earning cap to prevent a small number of accounts from monopolizing the entire pool

***

6. ### Anti-Sybil and Fairness Policy

AFX uses a multi-layered behavioral analysis system to ensure points are distributed to genuine users. Detection scope includes but is not limited to:

* Wash trading and self-trading behavior
* Coordinated wallet clusters and collaborative point farming
* Abnormal trading frequency or pattern anomalies
* Bot-driven activity

A **"Real Score" multiplier** is applied to each user's raw points. Users demonstrating genuine, diversified trading behavior will receive full or enhanced rewards. Accounts flagged for suspicious activity will have their allocation reduced or be excluded entirely.Detection methods and parameters are intentionally not disclosed and are continuously optimized. Retail users and API users are evaluated under their own independent scoring systems to account for their different trading characteristics.

***

7. ### Core Rules

* Points are non-transferable and non-tradeable
* All Season points accumulate and are redeemed together at TGE — nothing resets or expires
* Scoring criteria and weekly budgets may be adjusted between program phases; changes will be announced in advance
* All point distributions are final once published
* The protocol reserves the right to adjust or revoke points for any behavior determined to be manipulative or harmful
* Specific calculation formulas, weights, coefficients, and detection parameters are intentionally kept private to maintain system integrity

***

8. ### FAQ

**How often are points distributed?**

Once per week. The activity window runs Monday through Sunday (UTC), and points are released the following week.

**Do points reset when a Season ends?**

No. All points from every Season accumulate together and are redeemed at TGE at the same unified rate — nothing resets or expires.

**Is the points pool size fixed for each Season?**

Yes. Each Season has a fixed points pool, with the specific amount announced at the start of that Season.

**Can I earn points from trading, AFX LP Vault, and the Guild League at the same time?**

Yes. All three earning methods are calculated independently. Participating in multiple methods simultaneously maximizes your potential rewards.

**How do I join a guild?**

Find a Captain's guild invitation link in the AFX community. Once you join, your trading volume counts toward the guild's weekly ranking.

**I'm an API user — how is the API pool size determined?**

The API pool's share of weekly points is dynamically calculated based on API users' actual contribution to total protocol volume that week. The specific mechanism is not disclosed publicly.

**Is there a daily cap on how many points a single API user can earn?**

Yes. There is a daily cap within the API pool to ensure fair distribution among all API participants. Undistributed API points roll over to subsequent days within the same week and do not flow into the Retail pool.

**How does the anti-sybil system work? Will normal trading be penalized?**

The system is designed to identify clear manipulation. If you are genuinely trading — using diversified strategies, holding real positions, participating across multiple markets — you will not be negatively affected.

**What happens to testnet points?**

Testnet retroactive points will be announced within one week of mainnet launch and converted to tokens at TGE using the same unified exchange rate as mainnet points.


# Season 1

### Overview

Season 1 is the opening chapter of the AFX Mainnet Points Program. Every trade you make, every unit of liquidity you provide, and every guild contribution — all of it converts into points and ultimately into governance tokens at TGE.Points earned in Season 1 do not expire or reset at the end of this phase. They accumulate alongside points from all subsequent Seasons and are redeemed together at TGE. The earlier you participate, the more time you have to build your total.This phase runs for **8 weeks**, with both pools active simultaneously. All points will be merged with points from future Seasons and converted at TGE.

* **Start date:** May 25, 2026
* **End date:** July 20, 2026
* **Settlement:** Points from the previous week are settled every Monday at 00:00 UTC and distributed within the same week

***

### Points Pool Allocation

Season 1 features two independent pools and three ways to earn. Earning in one pool does not affect your allocation in another.

#### Trading + AFX LP Vault Combined Pool

Season 1 total: **2,885,714 points**, distributed at **360,714 points per week**.Trading points and AFX LP Vault points share this pool. Both can be earned at the same time and do not affect each other. The allocation between the two is adjusted dynamically based on platform conditions.

**Trading Points** Open to all active traders. Retail users and API users participate in separate sub-pools and do not compete with each other. Points are evaluated across multiple dimensions — trade execution, position contribution, and market diversity — to reward genuine, well-rounded trading behavior.

**AFX LP Vault Points** Open to users who deposit funds into the AFX LP Vault. Points are distributed based on each user's actual contribution to platform liquidity depth. During Season 1, the platform prioritizes building early liquidity depth — consistent liquidity provision is one of the primary ways to earn points in this phase.

#### Guild Pool

Season 1 total: **914,286 points**, distributed at **114,286 points per week**.Open to Captains and their guild members participating in the Guild League. Each week, guilds are ranked by total trading volume, and the Top 50 guilds share the weekly pool across a five-tier structure. If fewer than 50 guilds participate in a given week, any unallocated points roll into the discretionary pool.

**Weekly prize pool tier breakdown:**

|  Tier  | Guilds | Share of Weekly Pool |  Per Guild | Captain's Share |  Members' Share  |
| :----: | :----: | :------------------: | :--------: | :-------------: | :--------------: |
| Tier 1 |    1   |          20%         | 22,857 pts |  9% (2,057 pts) | 91% (20,800 pts) |
| Tier 2 |    3   |          20%         |  7,619 pts |   7% (533 pts)  |  93% (7,086 pts) |
| Tier 3 |    6   |          20%         |  3,810 pts |   6% (229 pts)  |  94% (3,581 pts) |
| Tier 4 |   10   |          20%         |  2,286 pts |   5% (114 pts)  |  95% (2,172 pts) |
| Tier 5 |   30   |          20%         |   762 pts  |   6% (46 pts)   |   94% (716 pts)  |

The members' share is further distributed based on each member's individual trading contribution during that week. Rankings reset every week — last week's top guild has no guaranteed advantage, and guilds of all sizes remain competitive.

***

### Season 1 Points Summary

|                Pool               | Weekly Distribution | Season 1 Total |
| :-------------------------------: | :-----------------: | :------------: |
| Trading + AFX LP Vault (Combined) |       360,714       |    2,885,714   |
|             Guild Pool            |       114,286       |     914,286    |
|               Total               |       475,000       |    3,800,000   |

***

### Notes

* All points earned in Season 1 carry over and accumulate with future Seasons — nothing resets or expires at TGE
* The allocation between trading and AFX LP Vault points is adjusted dynamically based on platform conditions
* If fewer than 50 guilds participate in a given week, unallocated guild points roll into the discretionary pool
* Full details for Season 2 will be announced before Season 1 ends


# Testnet Points

## Overview

This page documents the historical AFX testnet points program. The mainnet points program is live and documented separately in [Points](/points) and [Season 1](/points/season-1).

The AFX Points Program rewards users who contribute to the growth and health of the AFX protocol. Points represent your contribution to the platform and will be convertible to tokens at TGE (Token Generation Event).

The program operates on a "fixed output, dynamic distribution" model — a fixed number of points are distributed each period, and users compete for their share based on meaningful activity. This ensures predictable, sustainable incentives without runaway inflation.

## Testnet Program

### What is the Testnet?

The AFX testnet is an open testing environment where users can experience the full functionality of the platform using test tokens — with zero real capital at risk. The primary goal is to validate product functionality and stress-test the system under high-concurrency conditions.

### How to Participate

* Connect your wallet and register on the testnet
* Receive test tokens and begin trading or providing liquidity

### Testnet Reward Mechanism

Testnet participants will receive **retroactive point rewards** after mainnet launch. Points are allocated from a dedicated testnet pool — separate from the mainnet points pool — and will be convertible to tokens at TGE alongside mainnet points, at the same unified conversion rate.

### Prize Pool Structure

The testnet prize pool is split into two parts:

Total prize pool: **28,000 points**

* **Activity Pool (majority) (70% = 19,600 points)**— Rewarding real on-chain trading behavior; broader coverage and deeper engagement means a bigger share
* **Feedback Pool(30% = 8,400 points)** — Rewarding high-quality bug reports and product suggestions submitted via Discord

All testnet points are from a dedicated allocation separate from the mainnet points pool. At TGE, testnet and mainnet points are converted to tokens at the same unified rate.

### Part 1: Activity

Your activity score is calculated across multiple metrics. We reward genuine, diverse trading behavior — it's not about who generates the most volume, but who covers the most ground.

<table><thead><tr><th width="205.58203125">Metric</th><th width="308.1328125">What It Measures</th><th>Tiered scoring</th></tr></thead><tbody><tr><td><strong>Volume</strong></td><td>Cumulative notional value (USD)</td><td>≥ 12 M → <strong>10</strong> ; ≥ 10 M → 8 ; ≥ 8 M → 6 ; ≥ 6 M → 4 ; ≥ 4 M → 2 ; ≥ 1 M → 1 ; &#x3C; 1 M → 0</td></tr><tr><td><strong>Active Days</strong></td><td>Number of distinct days with trading activity</td><td>≥ 25 days → <strong>10</strong> ; ≥ 20 → 8 ; ≥ 15 → 6 ; ≥ 10 → 4 ; ≥ 5 → 2 ; ≥ 1 → 1</td></tr><tr><td><strong>Traded Pairs</strong></td><td>Number of distinct trading pairs traded</td><td>≥ 9 pairs → <strong>10</strong> ; 7–8 → 8 ; 5–6 → 6 ; 3–4 → 4 ; 1–2 → 2 ; 0 → 0</td></tr><tr><td><strong>Order Types</strong></td><td>Number of distinct order types used. Counted set: <strong>Market · Limit · Position TP/SL · Passive (post-only) · Reduce-only</strong></td><td>5 types → <strong>10</strong> ; 4 → 8 ; 3 → 6 ; 2 → 4 ; 1 → 2 ; 0 → 0</td></tr><tr><td><strong>Long &#x26; Short</strong></td><td>Whether you have both long and short trade records</td><td>Both directions → <strong>10</strong> ; one direction → 5 ; none → 0</td></tr><tr><td><strong>Leverage Tiers</strong></td><td>Number of distinct leverage buckets used during the historical testnet campaign. These buckets do not represent current mainnet leverage limits</td><td>5 buckets → <strong>10</strong> ; 4 → 8 ; 3 → 6 ; 2 → 4 ; 1 → 2 ; 0 → 0</td></tr><tr><td><strong>Position Lifecycle</strong></td><td>Whether you complete the full open → add → reduce → close cycle</td><td>Open + add + partial reduce + full close → <strong>10</strong> ; open + add + partial reduce → 8 ; open + add → 4 ; open only → 2</td></tr><tr><td><strong>Extreme Scenarios</strong></td><td>Whether you trigger forced liquidation and/or ADL</td><td>Both (liquidation + ADL) → <strong>10</strong> ; one → 5 ; none → 0</td></tr></tbody></table>

Generally, broader coverage across these dimensions leads to a higher score. The specific weight of each metric is determined internally and may be adjusted during the testnet period.

**Formula:** Your Activity Prize = (Your Score ÷ All Users' Total) × 19,600 points

### Part 2: Feedback

Great products are built on real user feedback. All submissions go through our Discord channel and are reviewed by the relevant community members. We value every piece of quality input.

| Type            | How It Works                                           |
| --------------- | ------------------------------------------------------ |
| **Bug Reports** | Submit on Discord → Tech community rates severity      |
| **Suggestions** | Submit on Discord → Product community rates usefulness |

Each submission is scored based on its severity (for bugs) or usefulness (for suggestions). Higher-impact contributions receive proportionally greater recognition.

**Formula:** Your Feedback Prize = (Your Score ÷ All Users' Total) × 8,400 points

### Testnet Timeline

* The testnet duration is determined by testing completion rather than a fixed end date
* When the testnet closes, all data is finalized — the closing moment serves as the automatic snapshot
* Approximately one week of preparation follows before mainnet launch
* Retroactive testnet points are published within one week of mainnet launch

### Sybil & Fairness Policy

AFX is committed to rewarding genuine participants. The platform employs a multi-dimensional behavioral analysis system to identify inauthentic activity, including but not limited to mass-created accounts, bot-driven actions, and coordinated farming patterns. Accounts flagged as Sybil may have their rewards reduced or removed entirely. Detection methods are not disclosed and are continuously refined.

## Mainnet Program

The mainnet points program is live. See [Points](/points) for the current program overview and [Season 1](/points/season-1) for the active season details.

## Rules & Notes

* Each pool is distributed pro-rata: your share = your score ÷ sum of all participants' scores
* Wash trading, self-trades, and any form of manipulation will result in full disqualification
* Duplicate bug reports are credited to the first reporter only
* The tech and product community members are the sole judges for feedback scoring
* The community reserves the right to adjust scoring criteria and final distributions
* Testnet points can be converted into token rewards based on participation and applicable terms
* Points are non-transferable and cannot be traded

## FAQ

<details>

<summary>Is there any financial risk during testnet?</summary>

No. The testnet uses test tokens only. No real funds are involved, and there is no possibility of financial loss.

</details>

<details>

<summary>Will my testnet points reduce the mainnet pool?</summary>

No. Testnet and mainnet points come from completely separate allocations. Participating in testnet does not affect mainnet rewards in any way.

</details>

<details>

<summary>How do I know if I'm flagged as a Sybil?</summary>

The platform does not disclose individual Sybil assessments. If you are participating genuinely and testing diverse features, you have nothing to worry about.

</details>

<details>

<summary>When will I see my testnet rewards?</summary>

Retroactive testnet points are handled as part of the broader points program. See the current points pages for the latest status.

</details>

<details>

<summary>Can I earn points from both trading and LP during testnet?</summary>

Yes. Both activities count toward your participation and feature coverage scores.

</details>


# Audits

The AFX bridge contract has been audited by Zellic. The report below covers the bridge contract scope described in the audit report and should not be read as a full-platform audit of every AFX component.

{% file src="/files/vF7OXfSSVWV16zAeYnbr" %}


# Welcome to AFX Learn

Free, plain-English guides on perpetual futures trading: how perps work, how to trade on-chain, funding rates, liquidation, stock and gold perps, and more. Start learning with AFX.

Perpetual futures let you trade price direction on crypto, stocks, metals, and indices — with leverage, no expiry, and no custody of the underlying asset. This hub covers everything you need to understand and trade on-chain perps: from first principles to step-by-step guides to market-specific explainers.

All guides are written for traders who want to understand what they're doing, not just follow steps. No hype. No price predictions.

### Where to Start

New to perpetual futures or on-chain trading? Start here in order:

1. [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — what on-chain perp trading is and how it works
2. [On-Chain Perps vs CEX Perps](/basics/on-chain-vs-cex-perps) — how DEX trading differs from centralized exchanges
3. [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) — a step-by-step walkthrough from wallet to first trade

Already familiar with perps? Jump directly to any section below.

### [Basics](/basics/what-is-a-perpetual-dex)

Core concepts every perp trader needs to understand — regardless of which platform you use.

| Guide                                                        | What it covers                                                                                         |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex)  | How on-chain perpetual exchanges work, and how they differ from traditional futures                    |
| [On-Chain Perps vs CEX Perps](/basics/on-chain-vs-cex-perps) | Custody, transparency, fees, liquidity, and asset access — side by side                                |
| [What Is a Funding Rate?](/basics/what-is-funding-rate)      | How funding payments keep perp prices anchored to spot — and what they signal about market sentiment   |
| [What Is Liquidation?](/basics/what-is-liquidation)          | What triggers automatic position closure, how to calculate your liquidation price, and how to avoid it |
| *More coming →*                                              | Leverage, margin types, mark price vs index price, open interest, and more                             |

### [How-To Guides](/how-to-guides/trade-stock-perpetuals-on-chain)

Step-by-step walkthroughs for trading, depositing, managing positions, and earning on AFX.

| Guide                                                                                                    | What it covers                                                                                       |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) | Connect wallet → deposit USDC → choose market → open position                                        |
| *More coming →*                                                                                          | How to set leverage safely, how to read a funding rate, limit vs market orders, stop-loss management |

### Markets & Assets

AFX lists perpetuals across crypto, equities, metals, and indices. These guides explain the mechanics and context for each market category.

| Guide                                                                             | What it covers                                                                                   |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| [Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain) | How equity perps work — MSTR, NVDA, TSLA, AAPL — trading stock price exposure 24/7, no brokerage |
| *More coming →*                                                                   | NVDA, TSLA, AAPL, XAG silver, SPX index perpetuals                                               |

***

### About These Guides

All content on this Learn Hub follows AFX's editorial standards:

* **No price predictions.** We explain how markets work, not where they're going.
* **Plain language first.** Technical accuracy without unnecessary jargon.
* **NFA on all trading content.** Perpetual futures carry a high risk of loss. Nothing here is financial advice. Availability of markets varies by jurisdiction.

Guides are reviewed and updated periodically. If something is out of date or unclear, refer to the [AFX Documentation](https://docs.afx.xyz/) for current platform specifics.

**Ready to trade?** [Open AFX →](https://app.afx.xyz/trade)


# What Is a Perpetual DEX? Guide to On-Chain Perpetual Futures

Learn what a perpetual DEX (perp DEX) is and how on-chain perpetual futures trading works. Explore funding rates, leverage, liquidations, benefits, risks, and self-custody.

A perpetual DEX, or decentralized perpetual exchange, lets you trade perpetual futures through a self-custody wallet. Perpetual futures have no expiry date. Collateral is typically deposited into protocol smart contracts rather than a company-controlled account.

This guide explains how a perp DEX works. It covers funding rates, leverage, liquidations, self-custody, benefits, and trading risks.

### Key Takeaways

* A perpetual DEX is a decentralized exchange for trading perpetual futures — leveraged contracts with no expiry date — settled on-chain via smart contracts.
* Perp DEXs use self-custody wallets, while trading collateral is typically held in protocol smart contracts.
* Core machinery includes smart contracts, price oracles, funding, margin, leverage, and liquidation controls.
* Traders can go long or short with leverage, but face real risks: volatility, liquidation, funding costs, and smart-contract risk.
* Some venues also list stock- and commodity-linked perpetuals, often settled in stablecoins like USDC.

### What Is a Perpetual DEX?

A perpetual DEX is a decentralized exchange (DEX) for trading perpetual futures contracts. These on-chain derivatives let you take a leveraged long or short position without a settlement or expiry date.

Two ideas combine in the name:

* Perpetual — the contract never expires, so you can hold a position for as long as your margin supports it, instead of rolling over monthly or quarterly futures.
* DEX (decentralized exchange) — trading is executed by smart contracts on a blockchain, and you trade from a self-custody wallet rather than depositing into a company-controlled account.

To keep a contract that never settles close to the spot price, perp DEXs use a funding rate. This periodic payment between long and short traders nudges the perpetual price toward spot.

In short, a decentralized perpetual exchange offers wallet-based access to leveraged derivatives. Availability and execution design vary by protocol and jurisdiction.

### Key Features of an On-Chain Perpetual DEX

A perpetual DEX is really a set of on-chain building blocks working together:

* Perpetual contracts — no expiry, so positions can be held indefinitely as long as margin requirements are met.
* Non-custodial trading — you trade from your wallet; collateral sits in audited smart contracts, not a custodial account.
* Price oracles — decentralized price feeds (e.g. Chainlink, Pyth) supply a reliable mark price so the protocol knows the "fair" value for PnL and liquidations.
* Funding rate mechanism — periodic payments between longs and shorts that keep the perpetual price anchored to spot.
* Margin & leverage — collateral backs your position and lets you amplify exposure; more leverage means more liquidation risk.
* Liquidity model — some perp DEXs use a virtual AMM (vAMM) or liquidity pools, others use an on-chain order book, and some are hybrids.
* Liquidation & risk engine — smart contracts continuously check margin ratios and close under-collateralized positions automatically, often backed by an insurance fund.
* Settlement asset — many venues settle everything in a stablecoin such as USDC, which simplifies margin and PnL across different markets.

Together these components replace the trusted middleman of a centralized derivatives exchange with transparent, auditable on-chain logic.

### How On-Chain Perpetual Futures Trading Works

The features above describe what a perp DEX offers; here's how the pieces interact in real time:

1. Collateralization. You deposit collateral (often a stablecoin like USDC) into a margin account governed by smart contracts. This collateral backs your positions and sets how much leverage you can take.
2. Trade execution. In vAMM or pool-based designs, a pricing curve simulates a counterparty. In order-book designs, your order matches against resting orders. Some protocols use hybrid or off-chain components.
3. Price anchoring. Oracles feed external spot prices to establish the mark price, which is used to calculate unrealized profit and loss (PnL) and to trigger liquidations.
4. Funding rate balancing. Because the contract never expires, funding payments flow between traders to keep it tethered to spot:
   1. If the perpetual price is above spot → longs pay shorts.
   2. If the perpetual price is below spot → shorts pay longs.
5. Risk & liquidation. Smart contracts monitor each position's margin ratio. If collateral drops below the maintenance threshold, the position is liquidated automatically, and an insurance fund may absorb any shortfall during extreme volatility.
6. Settlement. When you close a position, realized PnL updates your collateral balance.

   `PnL = (Exit Price − Entry Price) × Position Size ± Funding Payments − Fees`

   You can withdraw available collateral according to the protocol's withdrawal rules.

The result is a self-running loop — collateral, liquidity, oracles, funding, and liquidations — that reproduces the machinery of a centralized derivatives exchange without a central operator.

### How to Use a Perpetual DEX

Getting started is straightforward, but understand each step before committing capital:

1. Set up a non-custodial wallet. Use a wallet compatible with the perp DEX's blockchain and fund it with an accepted collateral asset (commonly USDC).
2. Connect to the exchange. Open the official site and connect your wallet. Always verify the URL to avoid phishing clones.
3. Deposit collateral. Approve and transfer your collateral into the protocol's margin contract. This acts as margin for leveraged positions.
4. Choose a market and direction. Pick a perpetual market (e.g. [BTC-USDC](https://app.afx.xyz/trade/BTCUSDC), or a stock/commodity perp like [MSTR-USDC](https://app.afx.xyz/trade/MSTRUSDC) or [XAU-USDC](https://app.afx.xyz/trade/XAUUSDC) where supported). Decide to go long (price up) or short (price down).
5. Set your leverage. Higher leverage increases both potential profit and the chance of liquidation. Beginners should start conservatively.
6. Place an order.
   1. Market order — fills immediately at the current price.
   2. Limit order — fills only at your chosen price.
   3. Many perp DEXs also support stop-loss and take-profit orders.
7. Monitor margin and funding. Watch your margin ratio, unrealized PnL, and funding payments. If your margin falls too low, your position can be liquidated.
8. Close or adjust. Exit any time; the protocol settles PnL, deducts fees/funding, and returns unused collateral to your wallet.

> *Tip: Start with small positions and low leverage to learn how funding rates and liquidation thresholds behave before scaling up. Not financial advice (NFA).*

### Benefits of Perpetual DEXs

* Self-custody. You control the wallet used to access the protocol. Trading collateral remains subject to smart-contract risk.
* Permissionless access. Anyone with a wallet can connect, subject to local laws.
* Transparency. Many protocols publish on-chain trades, funding, and liquidation data for independent review.
* No expiry. Perpetual contracts avoid the rollovers of dated futures.
* DeFi composability. Collateral and positions can interact with the broader on-chain ecosystem.
* Broadening markets. Some perp DEXs offer equity- and commodity-linked perpetuals settled in stablecoins. Market availability varies by venue and jurisdiction.

### Security in Perpetual DEXs

Perp DEXs replace trust in an intermediary with on-chain guarantees, but "decentralized" does not mean "risk-free." Key security aspects:

* Smart-contract enforcement. Order execution and liquidation run in code. Reputable protocols publish audits and run bug-bounty programs, though smart-contract risk can never be fully eliminated.
* Self-custody of funds. Assets remain in your wallet, avoiding exchange-insolvency risk — but you are responsible for your own keys.
* Decentralized oracles. Pulling prices from networks like Chainlink or Pyth reduces single-source manipulation risk.
* Insurance funds. Reserves can cover shortfalls when liquidations can't fully close a position in volatile markets.
* Auditable by anyone. On-chain data lets independent parties verify solvency and system health in real time.

### Risks of Perpetual Futures Trading on a DEX

Perp DEXs have different custody and execution trade-offs from centralized venues. Understand these risks before trading:

* Leverage & liquidation risk — leverage magnifies losses as well as gains; positions can be liquidated quickly.
* Funding costs — holding a position for a long time can erode returns if funding is persistently against you.
* Liquidity & slippage — thinner markets can mean worse fills than a large centralized venue.
* Oracle risk — faulty or manipulated price feeds can cause unfair liquidations.
* Smart-contract risk — bugs or exploits can put funds at risk despite audits.
* Regulatory uncertainty — derivatives access is restricted in some jurisdictions.

Perp DEXs offer transparency and control, but you must weigh technical, financial, and regulatory risks before committing capital. *This is not financial advice.*

### Perp DEX vs. Spot DEX and Centralized Exchanges

<table data-search="false"><thead><tr><th>Feature</th><th>Perp DEX</th><th>Spot DEX</th><th>Centralized Perp Exchange (CEX)</th></tr></thead><tbody><tr><td>Custody</td><td>Wallet access; collateral is held by protocol contracts</td><td>Usually wallet-based</td><td>Usually custodial</td></tr><tr><td>Contract expiry</td><td>None (perpetual)</td><td>N/A (spot only)</td><td>None (perpetual)</td></tr><tr><td>Leverage</td><td>Often available, within protocol limits</td><td>Usually none</td><td>Often available</td></tr><tr><td>Execution</td><td>On-chain, hybrid, or protocol-specific</td><td>Usually on-chain</td><td>Usually off-chain matching</td></tr><tr><td>Transparency</td><td>Varies by protocol and design</td><td>Usually on-chain activity</td><td>Varies by venue</td></tr><tr><td>Access</td><td>Wallet-based; restrictions may apply</td><td>Wallet-based; restrictions may apply</td><td>Account requirements vary</td></tr><tr><td>Main risks</td><td>Contract, oracle, liquidity, liquidation</td><td>Asset and smart-contract risk</td><td>Custody, counterparty, liquidation</td></tr></tbody></table>

### Perpetual DEX FAQs

**How does a perpetual DEX work?**

A perp DEX lets you deposit collateral into a smart contract and open a leveraged long or short on a perpetual futures market. Oracles supply the mark price, a funding rate keeps the contract tethered to spot, and an automated liquidation engine closes positions that fall below their margin requirement — all on-chain, without a central operator.

**What does "perpetual" mean in crypto?**

"Perpetual" refers to a futures contract with no expiry or settlement date. Instead of expiring, it uses a funding rate to stay close to the underlying spot price, so you can hold a leveraged long or short position indefinitely as long as you maintain enough margin.

**Is perpetual trading risky?**

Yes. Perpetual trading uses leverage, which magnifies both profits and losses, and positions can be liquidated if the market moves against you. You also face funding costs, oracle risk, and smart-contract risk. Use conservative leverage and risk management, and never trade more than you can afford to lose. *NFA.*

**What is the difference between an asset and its perpetual?**

Buying the spot asset means owning the asset itself. Trading its perpetual means taking a leveraged derivative position on its price — you can go long or short, you don't own the underlying, and you pay or receive funding to hold the position.

**Can you trade stocks or gold on a perpetual DEX?**

On some newer perp DEXs, yes. In addition to crypto, certain venues list equity and commodity perpetuals — for example stock perps (like MSTR or TSLA) and metals such as gold (XAU) — usually settled in a stablecoin like USDC and tradable around the clock.

### Conclusion

Perpetual DEXs bring leveraged futures trading fully on-chain. They combine no-expiry contracts, self-custody, transparent execution, and permissionless market access.

They also carry real risks, including leverage, funding costs, oracle exposure, and smart-contract risk. As liquidity deepens, decentralized perpetual exchanges are becoming core venues for on-chain derivatives and perpetual futures trading.

***

#### Keep learning

* Next: [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) — a step-by-step walkthrough.
* Related: [What Is a Funding Rate?](/basics/what-is-funding-rate) — understand periodic funding payments.
* Explore markets: [Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain) — learn how stock-linked perps differ from shares.
* Try it: Open a market on [AFX](https://app.afx.xyz/) and place a test position with small size. *NFA.*

*Disclaimer: This content is for general information and educational purposes only and is not financial, legal, or investment advice. Digital asset trading involves significant risk, including the possible loss of your entire position. You are solely responsible for your own decisions.*


# What Is a Funding Rate? How It Works in Perpetual Futures

Learn how funding rates work in perpetual futures, who pays them, how they affect holding costs, and why their calculation varies by platform.

A funding rate is a periodic payment associated with open perpetual futures positions. It helps keep a perpetual contract close to its reference price. On many venues, a positive rate means longs pay shorts. A negative rate means shorts pay longs. Calculation and settlement rules vary by platform.

> **NFA.** Perpetual futures are leveraged products that carry a high risk of loss.

### Why Perpetual Futures Need a Funding Rate

Standard futures contracts expire on a set date. At expiry, the futures price automatically converges with the spot price — that's the settlement mechanism.

Perpetual futures never expire. Without a settlement date, there's no built-in mechanism to keep the perpetual price aligned with spot. Left alone, the two prices would drift apart.

The funding rate solves this. When the perpetual trades above spot, a positive rate makes long positions more expensive to hold — pushing some traders to close longs or open shorts, which pulls the perpetual price back down. When the perpetual trades below spot, a negative rate discourages shorts and incentivizes longs, which pushes the price back up.

The result: perpetual prices stay tethered to spot without ever needing to settle.

### Positive vs. Negative Funding Rate

|                     | **Positive Funding Rate**                                  | **Negative Funding Rate**                                  |
| ------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- |
| **When it happens** | Perpetual price > spot price                               | Perpetual price < spot price                               |
| **Who pays**        | Longs pay shorts                                           | Shorts pay longs                                           |
| **Market signal**   | Bullish sentiment, excess long leverage                    | Bearish sentiment, excess short leverage                   |
| **Effect**          | Makes holding longs more expensive → pulls perp price down | Makes holding shorts more expensive → pushes perp price up |

A rate near zero means the perpetual and spot prices are closely aligned — neither side is paying much to hold.

### How Funding Fees Are Calculated

The funding fee is straightforward:

**Funding Fee = Position Size × Funding Rate**

**Example:**

* You hold a $10,000 long position
* The funding rate is **+0.01%** (paid every 8 hours)
* You pay: $10,000 × 0.01% = **$1 per 8-hour interval**
* Over 3 days (9 intervals): **$9 in total funding costs**

If the rate were **−0.01%** with the same long position, you would *receive* $1 per interval instead.

A few things to note:

* **Funding intervals** vary by platform — common intervals are every 1, 4, or 8 hours. Check the specific interval for each market you trade.
* **Leverage amplifies funding costs.** A 10x leveraged position carries the same dollar cost as a position 10× larger at 1x — because what matters is notional size, not margin size.
* **The rate changes continuously.** It fluctuates with the gap between perpetual and spot prices, so the fee you pay in the next interval may differ from the last.

On AFX, the current funding rate and countdown to the next interval are displayed in the trading interface for every market — including equity, metal, and index perpetuals.

### What Does the Funding Rate Tell You About the Market?

Beyond its mechanical purpose, the funding rate is a real-time gauge of market sentiment and leverage.

**Think of it as a thermometer for crowd positioning:**

| Funding Rate Level                    | What It Suggests                                             |
| ------------------------------------- | ------------------------------------------------------------ |
| High positive (e.g., +0.05%–0.10%+)   | Strongly bullish sentiment; high long leverage in the market |
| Mildly positive (e.g., +0.01%–0.03%)  | Moderately bullish; normal market conditions                 |
| Near zero (±0.01%)                    | Balanced positioning; perpetual close to spot                |
| Mildly negative (e.g., −0.01%–−0.03%) | Moderately bearish; more shorts than longs                   |
| High negative (e.g., below −0.05%)    | Strongly bearish sentiment; heavy short positioning          |

**What high positive funding can signal:** A high positive rate can indicate concentrated long positioning. Thresholds differ by asset, venue, and funding interval. Crowded leverage can increase liquidation risk, but funding alone does not predict a price reversal.

This is why experienced traders monitor funding rates alongside price action. A market can be rising but becoming more expensive and risky to trade long at the same time.

### Is a Negative Funding Rate Bullish?

This is one of the most searched questions around funding rates — and the answer is: **sometimes, yes.**

When the funding rate is deeply negative, shorts are dominant. Shorts are paying longs to hold their positions, which means:

1. There's significant bearish positioning in the market
2. Shorts face an ongoing cost to maintain their positions
3. If the price fails to keep falling, those shorts may close — creating buying pressure

In this sense, extreme negative funding can be a **contrarian signal**: when everyone is positioned short and paying for the privilege, the market may be closer to a bottom than a top.

However, negative funding is not a standalone buy signal:

* A fundamentally deteriorating asset can sustain negative funding for extended periods
* Funding rates can go more negative before reversing
* Always consider price trend, liquidity, and broader context alongside funding data

Use funding rates as one input among several, not as a predictive trigger on its own. (NFA)

### Funding Rates vs. Trading Fees

These are different and often confused:

|                       | **Funding Rate**                                            | **Trading Fee**                      |
| --------------------- | ----------------------------------------------------------- | ------------------------------------ |
| **Who receives it**   | The other side of your trade (longs → shorts or vice versa) | The exchange                         |
| **When it's charged** | At each funding interval (while position is open)           | At order execution (open and close)  |
| **Amount**            | Varies with market conditions                               | Fixed percentage set by the platform |
| **Direction**         | Can be positive or negative                                 | Always a cost to the trader          |

### FAQ

**What does the funding rate tell you?** The funding rate tells you the balance of demand between long and short traders in the perpetual market. A high positive rate signals crowded long positioning and excess leverage. A high negative rate signals crowded short positioning. Near-zero rates indicate a balanced market where the perpetual price is close to spot.

**How do you calculate the funding rate?** Your funding fee = Position notional size × Funding rate. For example, a $5,000 position at a funding rate of 0.01% pays or receives $0.50 per interval. The funding rate itself is determined by the platform based on the gap between the perpetual's mark price and the spot index price, usually with an interest rate component added.

**Who pays who if the funding rate is positive?** If the funding rate is positive, traders with long positions pay traders with short positions. The logic: when the perpetual trades above spot (driving a positive rate), longs are the ones creating the premium, so they pay to compensate shorts for holding the other side.

**Who pays the funding rate?** The funding rate is paid by traders to other traders — not to the exchange. Which side pays depends on the rate's direction: positive rate → longs pay shorts; negative rate → shorts pay longs. The exchange facilitates the transfer but does not collect it as revenue.

### Key Takeaways

* A funding rate is a periodic payment associated with open long and short positions
* Positive rate: perp > spot; longs pay shorts
* Negative rate: perp < spot; shorts pay longs
* Funding fee = position notional size × rate (leverage amplifies the dollar cost)
* Extreme positive rates signal crowded long leverage and potential fragility
* Extreme negative rates can be a contrarian signal — but not a reliable standalone buy trigger

***

### Related guides

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — learn the core mechanics behind on-chain perpetuals.
* [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) — see where to review funding before opening a position.
* [Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain) — understand funding when trading stock-linked markets.

**Trade on AFX →** [app.afx.xyz/trade](https://app.afx.xyz/trade) *(NFA — perpetual futures carry a high risk of loss. Availability varies by jurisdiction.)*


# What Is Liquidation in Perpetual Trading? How It Works & How to Avoid It

Liquidation is the automatic closure of a leveraged position when your margin falls below the required level. Learn what triggers it, what happens to your funds, and how to avoid it.

Liquidation is the automatic closure of a leveraged perpetual position when your margin balance falls below the maintenance margin level required to keep it open. The protocol closes your position and takes the collateral assigned to it. You don't lose more than you deposited — but you do lose the margin for that position.

Understanding liquidation is essential before using leverage. It's not a punishment or an error — it's a core part of how leveraged trading manages risk.

> **NFA.** Perpetual futures are leveraged products that carry a high risk of loss.

### Why Liquidation Exists

When you open a leveraged position, you're controlling a notional value larger than your actual collateral. If the market moves against you far enough, your losses can theoretically exceed your deposit.

To prevent traders from going into negative balances — and to protect the protocol from bad debt — perpetual trading platforms enforce a minimum margin level called the **maintenance margin**. If your margin drops below this threshold, the protocol liquidates your position automatically, before you can lose more than you put in.

Think of it as a hard floor: the protocol would rather close your trade at a loss than risk being left holding an uncollateralized position.

### Your Liquidation Price

Every leveraged position has a **liquidation price** — the specific mark price at which your position would be automatically closed.

The liquidation price is set the moment you open a trade. It depends on three things:

1. **Your entry price** — where you opened the position
2. **Your leverage** — higher leverage means the liquidation price is closer to your entry
3. **Your margin** — more collateral relative to position size means more buffer

**Rough rule of thumb:**

* At **10x leverage**, a \~10% move against you can trigger liquidation
* At **5x leverage**, it takes a \~20% move
* At **2x leverage**, it takes a \~50% move

The liquidation price is always displayed on your position panel before and after you open a trade. On AFX, you'll see it listed alongside your entry price and unrealized PnL. Check it before confirming any order.

### What Happens When You're Liquidated

The process happens automatically when the **mark price** (not the last traded price — the oracle-derived reference price) reaches your liquidation threshold:

1. **Position is closed** — the protocol forcibly closes your position at the best available price
2. **Remaining margin is taken** — your collateral for that position is used to cover the loss
3. **Insurance fund covers shortfall** — if the position closes at a price worse than your liquidation price (gap risk in fast markets), the protocol's insurance fund covers the difference
4. **If insurance fund is depleted** — in extreme cases, an auto-deleveraging (ADL) mechanism may partially unwind profitable positions on the other side to cover the loss. This is rare and a last resort.

**You do not receive any remaining margin once liquidation is triggered.** The entire collateral assigned to that position is gone. This is why managing your liquidation price matters — even a small buffer can mean the difference between surviving a volatile candle and losing your margin entirely.

### Isolated Margin vs Cross Margin

How much of your funds are at risk during liquidation depends on your margin mode:

#### Isolated Margin

Each position has its own dedicated margin. Only the collateral you explicitly assigned to that position can be liquidated — the rest of your account balance is protected.

* **Advantage:** One position getting liquidated doesn't affect others
* **Disadvantage:** A single position can be liquidated without access to your broader balance as a buffer

#### Cross Margin

All available collateral in your account is shared across all open positions. The platform draws from your full balance to keep any position from being liquidated.

* **Advantage:** More cushion before any single position hits its liquidation price
* **Disadvantage:** A losing position can draw down your entire account balance, potentially affecting multiple positions at once

Most beginners start with isolated margin — it limits the blast radius of any single bad trade.

### How to Avoid Liquidation

Liquidation is avoidable with disciplined position management:

**1. Use lower leverage** The higher your leverage, the closer your liquidation price is to your entry. Starting at 2x–5x gives significantly more room for price movement before a liquidation threshold is hit. Treat higher leverage as an advanced tool, not a default setting.

**2. Add margin to an at-risk position** If the market moves against you and your liquidation price is getting close, you can deposit more collateral into the position. This lowers your effective leverage and moves the liquidation price further away.

**3. Set a stop-loss before your liquidation price** A stop-loss order exits your position at a price you choose — before the protocol forces a liquidation. This means you control the exit, keep any remaining margin, and avoid the full loss of collateral that liquidation triggers. Set your stop-loss with enough buffer above the liquidation price to account for fast market moves.

**4. Monitor your margin ratio** Most trading interfaces display a margin ratio or health indicator that shows how close you are to liquidation. Check it regularly, especially during volatile market periods. On AFX, this is visible in real time on your position panel.

**5. Account for funding rate drag** Funding payments reduce your margin balance over time if you're on the paying side. A position that starts well-capitalized can creep toward its liquidation price if a high funding rate slowly erodes your margin. Factor expected funding costs into your position sizing. See [What Is a Funding Rate?](/basics/what-is-funding-rate)

### Liquidation vs Stop-Loss: Key Difference

These are often confused:

|                     | **Stop-Loss**                              | **Liquidation**                                     |
| ------------------- | ------------------------------------------ | --------------------------------------------------- |
| **Triggered by**    | A price level you set                      | The protocol's maintenance margin threshold         |
| **Who controls it** | You                                        | The protocol                                        |
| **Outcome**         | Position closed; remaining margin returned | Position closed; all margin for that position taken |
| **Control**         | Fully in your hands                        | Automatic, no override                              |

A stop-loss is not a protection against liquidation — it's a tool to exit a position *before* liquidation takes your margin. The two work together: set a stop-loss above your liquidation price to keep control of your exit.

### FAQ

**What happens when you get liquidated in crypto?** Your position is automatically closed by the protocol when your margin falls below the maintenance margin level. The collateral assigned to that position is taken to cover the loss. You don't owe anything beyond what you deposited, but you lose that margin entirely.

**Do you lose all your money in liquidation?** You lose the margin assigned to the liquidated position — not necessarily your entire account balance. If you're using isolated margin, only the collateral for that specific position is at risk. If you're using cross margin, your full account balance acts as a buffer, but a large loss can draw it down significantly.

**What is the liquidation price?** The liquidation price is the specific mark price at which your position would be automatically closed. It's calculated at the moment you open the trade based on your entry price, leverage, and collateral amount. It's displayed in your position panel and doesn't change unless you add or remove margin.

**How do you avoid liquidation in crypto perpetual trading?** Use lower leverage, set a stop-loss order above your liquidation price, monitor your margin ratio regularly, and add margin if a position moves against you. Accounting for funding rate costs before entering a long-duration trade also helps prevent gradual margin erosion.

***

### Internal Links

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — how on-chain perp protocols handle liquidations via smart contracts
* [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) — where to find your liquidation price and margin ratio while trading
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — how funding payments can slowly erode margin and bring a position closer to liquidation
* [On-Chain Perps vs CEX Perps](/basics/on-chain-vs-cex-perps) — how liquidation mechanisms differ between DEX and centralized platforms

**Trade on AFX →** [app.afx.xyz/trade](https://app.afx.xyz/trade) *(NFA — perpetual futures carry a high risk of loss. Availability varies by jurisdiction.)*


# On-Chain Perps vs CEX Perps: Key Differences Explained (2026)&#x20;

On-chain perps keep your funds in your own wallet; CEX perps hand custody to the exchange. Compare custody, fees, transparency, liquidity, and asset access — and see when each makes sense.

The core difference is custody. On a centralized exchange (CEX), your collateral is held by the exchange. On an on-chain perp DEX, it stays in your own wallet until you deposit it into a smart contract — and you can withdraw it at any time, without asking anyone's permission.

That single structural fact shapes everything else: counterparty risk, transparency, what assets you can trade, and who can access the market. This article breaks down each dimension so you can evaluate which model fits your needs.

> **NFA.** Perpetual futures are leveraged products that carry a high risk of loss. Availability varies by jurisdiction.

### At a Glance: The Core Comparison

<table data-header-hidden data-search="false"><thead><tr><th></th><th></th><th></th></tr></thead><tbody><tr><td></td><td><strong>On-Chain Perps (DEX)</strong></td><td><strong>CEX Perps</strong></td></tr><tr><td><strong>Custody</strong></td><td>Your wallet; funds in smart contract only while trading</td><td>Exchange holds your funds</td></tr><tr><td><strong>Account required</strong></td><td>No — connect a wallet</td><td>Yes — email, password, KYC</td></tr><tr><td><strong>Transparency</strong></td><td>Every trade, position, and liquidation on-chain</td><td>Exchange reports only</td></tr><tr><td><strong>Withdrawal</strong></td><td>Permissionless, any time</td><td>Subject to platform rules and processing times</td></tr><tr><td><strong>Fees</strong></td><td>Protocol fee + gas (minimal on L2)</td><td>Maker/taker structure, no gas</td></tr><tr><td><strong>Liquidity</strong></td><td>Growing rapidly, major pairs competitive</td><td>Deepest liquidity, especially for large orders</td></tr><tr><td><strong>Leverage</strong></td><td>Typically 5x–40x</td><td>Up to 100x on some platforms</td></tr><tr><td><strong>Market hours</strong></td><td>24/7, no close</td><td>24/7 for crypto; restricted for other assets</td></tr><tr><td><strong>Asset range</strong></td><td>Crypto + equity, metal, and index perps</td><td>Primarily crypto</td></tr><tr><td><strong>Counterparty risk</strong></td><td>Protocol smart contracts</td><td>Exchange solvency</td></tr><tr><td><strong>Smart contract risk</strong></td><td>Yes</td><td>No</td></tr></tbody></table>

### Custody: The Structural Divide

On a CEX, you deposit funds into an account the exchange controls. You trust the platform to hold your money honestly, execute your trades accurately, and return your funds when requested. When that trust breaks — as it did with FTX in 2022 — users have no on-chain recourse. The exchange held the keys; the exchange decided what happened next.

On an on-chain perp DEX, you hold your private keys. When you trade, a smart contract locks only the margin you explicitly deposit for a given position. Outside of that, nothing leaves your wallet. If you choose to stop trading, you withdraw — the protocol cannot prevent it.

This is the difference between **institutional custody** (you trust someone else) and **self-custody** (you trust math and code). Both carry risk — a CEX can fail, and a smart contract can have vulnerabilities — but the nature of the risk is different, and the degree of control is not.

### Transparency

On a CEX, you see your account balance and trade history as reported by the exchange. You cannot independently verify that the exchange's stated reserve matches reality, or that your reported price is accurate, or that liquidations happened when claimed. Exchanges can be audited, but audits lag real time.

On a DEX, every order, fill, funding payment, and liquidation is a blockchain transaction — publicly indexed, timestamped, and verifiable by anyone. You can audit the protocol's total open interest, check any position's margin level, and verify your own trade history against the chain. This is what "trustless" means in practice: you don't need to trust a company's reporting because the ledger is open.

### Access and Account Requirements

CEXs require account creation, identity verification (KYC), and in some cases geographic restrictions determined by the platform's licensing. For many users globally, this creates friction or outright barriers.

A perp DEX has no concept of an account in the traditional sense. You connect a wallet address — that address *is* your account. No email, no password, no document uploads. Any wallet anywhere in the world can interact with the protocol's smart contracts.

Note: on-chain perp platforms may still apply geographic access controls at the front-end (web interface) level to comply with local regulations. Check a platform's terms of service for your jurisdiction before trading.

### Fees

**CEX fees** follow a maker/taker model. Makers (who add liquidity via limit orders) typically pay less than takers (who fill existing orders with market orders). High-volume traders unlock discounts. There are no gas fees, but withdrawals carry a fixed fee per asset.

[**DEX fees**](https://docs.afx.xyz/) consist of a protocol fee (charged per trade, typically as a percentage of notional) plus blockchain gas. Gas costs on modern Layer 2 networks are minimal — often under $0.10 per trade. The protocol fee is fixed regardless of order type or volume.

The practical difference is small for most trade sizes on L2 DEXs. For very large institutional-scale orders, CEX maker rebates can make CEXs more cost-efficient. For smaller traders or those avoiding KYC overhead, DEX total costs are comparable.

### Liquidity and Execution

CEXs concentrate liquidity from professional market makers and institutional traders. Major pairs like BTC and ETH have deep order books with tight spreads, meaning large market orders execute with minimal price impact. For active traders running high-frequency or large-size strategies, this remains a meaningful edge.

On-chain perp liquidity has grown substantially — decentralized perp volumes reached $6.7 trillion in 2025, up 346% year-over-year, representing roughly 7.8% of CEX volume according to public industry data. For standard trade sizes on major pairs, slippage on leading DEXs is now competitive with mid-tier CEXs. Thinner markets and less-traded assets still show more slippage.

Execution speed differs in kind, not just degree. CEX trades settle on internal servers in milliseconds. DEX trades confirm on-chain, typically in a few seconds on modern L2 networks, but subject to block times and occasional congestion.

### Asset Availability: Where On-Chain Now Leads

This is where the comparison shifts in favor of on-chain DEXs for a specific category of trader.

CEXs primarily offer crypto perpetuals. Stock-linked derivatives and commodity contracts face heavy regulatory restrictions in most jurisdictions, so few CEXs can offer them to retail users globally.

On-chain perp platforms are opening up a different asset universe. On AFX, you can trade perpetuals on:

* **Crypto**: BTC, ETH, SOL, and others
* **Equity perps**: MSTR, NVDA, TSLA, AAPL — stock-linked perpetuals with no expiry
* **Metal perps**: XAU (gold), XAG (silver), settled in USDC
* **Index perps**: SPX (S\&P 500)

All of these trade **24/7** — including weekends and holidays, when traditional stock markets are closed. This is a structural advantage that no CEX can offer within its regulatory constraints. For the mechanics of equity perps, see [Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain).

### Which Should You Use?

Neither is universally better. They serve different needs.

**On-chain perps make more sense when you:**

* Want to keep custody of your funds and avoid exchange counterparty risk
* Prefer not to create an account or submit identity documents
* Want access to equity, commodity, or index perps trading 24/7
* Value being able to verify your own trades and the protocol's health on-chain

**CEX perps make more sense when you:**

* Trade at high frequency or very large size where liquidity depth and execution speed matter most
* Prefer the user experience of a traditional trading interface without managing a crypto wallet
* Are in a jurisdiction with clear regulatory guidance for CEX-based crypto derivatives

Many active traders use both — CEXs for crypto-heavy execution and on-chain platforms for asset classes CEXs cannot offer.

### FAQ

**What is on-chain perps?** An on-chain perpetual (on-chain perp) is a perpetual futures contract where order matching, settlement, collateral custody, and liquidations all happen through smart contracts on a blockchain. Users trade directly from a self-custody wallet with no centralized intermediary holding their funds.

**What is perps CEX?** A CEX perp is a perpetual futures contract offered on a centralized exchange. The exchange acts as a counterparty and custodian: it holds your deposited funds, matches your orders on its internal systems, and manages liquidations via its own risk engine.

**What is the difference between a CEX and a DEX?** The fundamental difference is custody and trust model. A CEX is a company that holds your funds and operates its own matching engine — you trust the company. A DEX is a set of smart contracts on a blockchain — your funds stay in your wallet, and trades settle on-chain. See [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) for a full explanation.

**Are perps risky?** Yes — particularly with leverage. Both on-chain and CEX perps can result in full liquidation of your margin if the market moves against your position. On-chain perps carry the additional risk of smart contract vulnerabilities. CEX perps carry exchange counterparty risk. In either case, only trade with capital you can afford to lose entirely. (NFA)

***

### Internal Links

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — how on-chain perp protocols work under the hood
* [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) — a step-by-step walkthrough
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — how funding payments work on both CEX and DEX perps
* [What Is Liquidation?](/basics/what-is-liquidation) — what happens when margin runs out
* [Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain) — equity and commodity perps available 24/7 on-chain

**Trade on AFX →** [app.afx.xyz/trade](https://app.afx.xyz/trade) *(NFA — perpetual futures carry a high risk of loss. Availability varies by jurisdiction.)*


# Trade Stock Perpetuals On-Chain: A Complete Guide (2026)&#x20;

Learn how to trade stock perpetuals on-chain. Explore equity perpetual futures, USDC collateral, long and short positions, funding rates, leverage, and liquidation risk.

## Trade Stock Perpetuals On-Chain: A Complete Guide

A stock perpetual is a perpetual futures contract that tracks the price of an equity — like Tesla, Nvidia, or MicroStrategy — instead of a cryptocurrency. Trading them on-chain means you take a leveraged long or short position on that stock's price directly from your own wallet, settled in a stablecoin such as USDC, with no brokerage account and no market-hours restriction.This guide explains what stock perpetuals are, how they differ from owning the actual shares, how the on-chain version works under the hood, the exact steps to place your first trade, and the risks you need to respect before you do. Trading leveraged derivatives carries a real risk of losing your entire margin — this is education, not financial advice.

### Key Takeaways

* A stock perpetual ("stock perp") is a perpetual futures contract whose price tracks an equity (e.g. [TSLA](https://app.afx.xyz/trade/TSLAUSDC), [NVDA](https://app.afx.xyz/trade/NVDAUSDC), [MSTR](https://app.afx.xyz/trade/MSTRUSDC), [AAPL](https://app.afx.xyz/trade/AAPLUSDC)) rather than a token — it has no expiry and lets you go long or short with leverage.
* Trading stock perps on-chain means settlement happens through smart contracts and you keep self-custody of your collateral — you never hand shares or cash to a broker.
* You do not own the underlying stock. There are no voting rights, no dividends, and no share certificate — you are trading price exposure, collateralized and settled in USDC.
* On-chain stock perps trade around the clock, not just during traditional market hours, and are permissionless to access from a wallet.
* The mechanics — margin, leverage, funding rate, liquidation — are identical to crypto perps. The added consideration is that equities react to earnings, macro news, and market-hours gaps.

### What Are Stock Perpetuals?

A stock perpetual is a type of perpetual futures contract in which the tracked asset is a publicly listed stock instead of a cryptocurrency. The contract's price follows the stock — say, Nvidia — and you profit or lose based on where that price moves relative to your entry.Two properties define it:

* Perpetual — the contract never expires. Unlike a traditional stock future or an option, there is no settlement date to roll over. You hold the position for as long as your margin supports it.
* Synthetic price exposure — you are trading a contract *referenced* to the stock, not the stock itself. No shares change hands. That is what lets an on-chain venue offer equity exposure without a brokerage, a transfer agent, or a stock exchange in the loop.

Because the contract references a stock rather than delivering one, a stock perp can be offered anywhere the collateral asset (USDC) and the price feed exist — which is what makes an on-chain, 24/7, wallet-based version possible.

### Stock Perpetuals vs. Owning the Stock

This is the distinction most newcomers miss, so it's worth being blunt about it:

<table data-search="false"><thead><tr><th></th><th>Owning the stock</th><th>Stock perpetual (on-chain)</th></tr></thead><tbody><tr><td>What you hold</td><td>Actual shares of the company</td><td>A contract tracking the share price</td></tr><tr><td>Ownership rights</td><td>Voting, dividends, shareholder status</td><td>None — price exposure only</td></tr><tr><td>Direction</td><td>Mainly long (buy to profit from a rise)</td><td>Long or short</td></tr><tr><td>Leverage</td><td>Limited / margin account required</td><td>Built in</td></tr><tr><td>Trading hours</td><td>Exchange hours (with some extended sessions)</td><td>Around the clock</td></tr><tr><td>Access</td><td>Brokerage account, KYC, jurisdiction rules</td><td>Wallet-based, permissionless</td></tr><tr><td>Custody</td><td>Broker / custodian holds your shares</td><td>Self-custody of collateral on-chain</td></tr><tr><td>Settlement asset</td><td>Fiat currency</td><td>USDC (stablecoin)</td></tr></tbody></table>

The trade-off is simple: a stock perp gives you flexible, leveraged, always-on price exposure and self-custody — but none of the ownership that comes with holding real shares. If your goal is long-term equity ownership with dividends and voting rights, buy the stock. If your goal is to trade the price, long or short, with leverage and without a broker, that is what a stock perp is for.

### Why Trade Stocks as On-Chain Perpetuals?

Stock perps sit in a genuinely new niche, and the appeal comes down to a few structural advantages:

* Go short as easily as long. Shorting a stock through a traditional broker means borrowing shares, paying borrow fees, and clearing eligibility hurdles. A stock perp treats short and long symmetrically — one click either way.
* Trade outside market hours. Equity markets close; crypto rails don't. A major earnings report or macro headline that lands after the closing bell can be traded immediately on-chain, instead of waiting for the next session's open.
* One collateral asset, many markets. Your USDC balance can back a Bitcoin perp, a gold perp, and a Tesla perp from the same wallet — no separate brokerage, no currency conversion.
* Self-custody. Your collateral stays under your own keys until a position is opened, and returns to your wallet when you close. There is no company balance sheet holding your funds between trades.
* Permissionless access. No account approval queue — if you have a wallet and USDC, you can access the market. (Availability of specific markets can still depend on where you are; always check local rules.)

For traders who already live in DeFi and want equity exposure without leaving self-custody, stock perps close a gap that used to force a choice between a crypto wallet and a stock brokerage.

### How On-Chain Stock Perpetuals Work

Mechanically, a stock perp works like any other perpetual — the equity reference just changes what the price feed points at. Here's the machinery:

1. [Price oracle](https://docs.afx.xyz/trading-rules/oracle-price). An on-chain oracle streams the reference stock's price into the protocol. This is the anchor everything else is measured against.
2. [Margin and leverage](https://docs.afx.xyz/trading-rules/margin-modes). You post USDC as margin (collateral). Leverage multiplies your exposure — e.g. 5x margin controls a position five times the size of your collateral. Leverage magnifies gains *and* losses equally.
3. Long or short. Open long if you expect the stock to rise, short if you expect it to fall. Your profit and loss tracks the reference price against your entry.
4. [Funding rate](https://docs.afx.xyz/trading-rules/funding-rate). Because the contract never expires, a periodic funding rate is exchanged between longs and shorts to keep the perp price tethered to the reference price. When the perp trades above reference, longs pay shorts; below, shorts pay longs. It's a balancing mechanism between traders, not a platform fee.
5. [Liquidation](https://docs.afx.xyz/trading-rules/liquidation). Every position has a liquidation price. If the market moves against you far enough that losses approach your margin, the protocol automatically closes the position to prevent further loss — and you lose that margin. Higher leverage puts the liquidation price closer to your entry.
6. On-chain settlement. Opening, funding, and closing all settle through smart contracts. When you close, your remaining margin plus or minus PnL returns to your wallet.

The simplified PnL for a long position:PnL ≈ (Exit price − Entry price) / Entry price × Position sizeFor a short, the sign flips — you profit when the exit price is below your entry.

### How to Trade Stock Perpetuals On-Chain, Step by Step

Here's the full process, start to finish, done self-custodially from your own wallet.

**Step 1** — Connect a self-custody wallet. Use a wallet you control. Your collateral stays under your keys until you actually open a position. (Some on-chain venues, such as [AFX](https://www.afx.xyz/), also let you fund via an email-based account, but the trade still settles on-chain.)

**Step 2** — Fund with USDC. Stock perps are collateralized in stablecoins, almost always USDC. Add an amount you'd be genuinely comfortable losing entirely — keep it small while you're learning.

**Step 3** — Pick a stock market. Choose the equity you want exposure to (for example TSLA, NVDA, MSTR, or AAPL). Start with a large, widely-followed name rather than an illiquid one — deeper liquidity means tighter spreads and cleaner fills.

**Step 4** — Choose direction and set low leverage. Decide long or short. Then keep leverage low — 2x to 5x — while you learn. High leverage feels exciting and liquidates fast. Where the venue supports it, prefer isolated margin so one bad trade can't drain your whole balance.

**Step 5** — Set size, stop-loss, and take-profit. Enter your position size. Before you confirm, set a stop-loss (an automatic exit if the trade goes against you) — this is non-negotiable. Set a take-profit too, so you lock gains instead of giving them back.

**Step 6** — Place the order. Use a market order to enter immediately at the current price, or a limit order to enter only at a price you choose. Confirm — and note your liquidation price one more time before you do.

**Step 7** — Manage the position. Watch three things: your margin, your liquidation price, and funding. Remember that equities react hard to earnings dates and macro news — a stock perp can gap on a report that a crypto perp would never see. If the trade moves your way, consider trailing your stop-loss up to protect gains.

**Step 8** — Close. Close manually to take profit or cut a loss, or let your stop-loss / take-profit do it. Your remaining margin returns to your self-custody balance on-chain.

> *Tip (NFA): Your first few trades should be about learning the mechanics — fills, funding, liquidation price — not about making money. Size them so a total loss wouldn't matter.*

### Risk Management for Stock Perps

Every risk that applies to crypto perps applies here, plus a few equity-specific ones. These rules are non-negotiable:

* Keep leverage low. Stay at 2x–5x until you have real, repeated experience. Leverage is the fastest way to get liquidated.
* Always use a stop-loss. Decide your maximum loss *before* you enter and let the stop enforce it.
* Respect earnings and macro events. Stocks gap on earnings, guidance, Fed decisions, and index rebalances. A position held through an earnings release can move violently while you sleep. Size accordingly or stand aside.
* Mind the funding rate on multi-day holds. Funding accrues while you hold. On a leveraged position kept for days, it adds up.
* Size so one loss can't hurt you. A common rule is risking no more than 1–2% of your balance on a single trade.
* Only risk money you can afford to lose entirely. No rent, no savings, no borrowed funds.

### Common Mistakes to Avoid

* Treating a stock perp like owning the stock. You have no dividends, no votes — only price exposure. Don't "hold for the long term" a leveraged contract that pays funding.
* Too much leverage, too soon. The number-one account killer.
* Trading through earnings without a plan. The single biggest equity-specific trap.
* No stop-loss. Hoping a losing trade "comes back" instead of cutting it.
* Ignoring funding costs on positions held for days.

### Stock Perps vs. Crypto Perps: What's the Same, What's Different

If you already trade crypto perps, the muscle memory transfers almost completely. The order form, leverage, funding rate, and liquidation logic are the same. The differences to internalize:

| Dimension              | Crypto perps                                         | Stock perps                                                                                                         |
| ---------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| Order form & mechanics | Margin, leverage, funding, liquidation               | Identical                                                                                                           |
| Event risk             | Unscheduled — runs 24/7, no earnings calendar        | Scheduled — earnings dates, Fed meetings, index rebalances concentrate volatility into predictable moments          |
| Reference-hours gaps   | Underlying trades continuously, no session close     | Underlying's primary market has open/close hours; news during closed hours can gap the perp when sentiment reprices |
| Correlation            | More idiosyncratic — tokens often move independently | Clustered — tech names move together; a broad market selloff can hit every stock perp at once                       |

A venue like [AFX](https://www.afx.xyz/) illustrates the crossover in practice: the same on-chain, USDC-collateralized, self-custodial account can hold crypto perps, commodity perps (such as gold and silver), and stock perps side by side — so a trader can rotate exposure across asset classes without leaving self-custody or juggling multiple platforms.

### Frequently Asked Questions

**Can you trade stock perpetuals on-chain?**&#x20;

Yes. Newer on-chain perpetual DEXs list stock perpetuals — perpetual futures that track equities like [Tesla](https://app.afx.xyz/trade/TSLAUSDC), [Nvidia](https://app.afx.xyz/trade/NVDAUSDC), or [MicroStrategy](https://app.afx.xyz/trade/MSTRUSDC) — settled in USDC and traded directly from a self-custody wallet, without a traditional brokerage account.

**Do I own the stock when I trade a stock perpetual?**&#x20;

No. A stock perpetual is a contract that tracks the share price. You get leveraged long-or-short price exposure, but no shares, no dividends, and no voting rights.

**Why trade a stock perp instead of buying the shares?**&#x20;

To go short as easily as long, to use leverage, to trade around the clock instead of only during market hours, and to keep your collateral in self-custody. If you want actual ownership, dividends, or voting rights, buy the shares instead.

**Can you trade perpetuals on Robinhood?**

&#x20;Robinhood is a traditional brokerage and does not offer on-chain perpetual futures in the way a perp DEX does; its equity products are actual shares (with some derivatives in select markets). On-chain stock perps are a different product — synthetic, leveraged, self-custodial contracts traded from a crypto wallet. Always check what a given platform actually offers and what's available in your jurisdiction.

**Is trading stock perpetuals risky?**&#x20;

Yes, very. Leverage means a single position can lose your entire margin, and equities add scheduled event risk — earnings and macro news can gap the price sharply. Beginners should use low leverage (2x–5x), always set a stop-loss, and start small.

**What happens to my stock perp during earnings?**&#x20;

The reference stock can move sharply on an earnings release, which moves your perp's price and can trigger liquidation if you're over-leveraged. Many traders reduce size or close positions around scheduled earnings to avoid the gap risk.

**How much do I need to start?**&#x20;

You can start with a small amount — the key is that it should be money you can afford to lose entirely. Keep positions small and leverage low while you learn the mechanics.

### Conclusion

Stock perpetuals bring equity exposure onto the same on-chain rails as crypto perps: leveraged, long-or-short, always-on, and self-custodial, settled in USDC. They are a powerful way to *trade the price* of stocks like Tesla or Nvidia without a brokerage — but they are not stock ownership, and they carry the full risk of leveraged derivatives plus the scheduled volatility of equities. Learn the mechanics on a small position, respect the risk rules, and never trade money you can't afford to lose.Keep learning:

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — the foundation for everything above
* [How to Trade Perpetuals On-Chain](/how-to-guides/how-to-trade-perpetuals-on-chain-a-step-by-step-guide) — the full order-placement walkthrough
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the mechanism that keeps a perp tethered to its reference
* [On-Chain Perps vs. CEX Perps](/basics/on-chain-vs-cex-perps) — how self-custodial trading compares to a centralized exchange

Ready to see it live? Explore markets on [app.afx.xyz](https://app.afx.xyz/trade).

***

*Disclaimer: This article is for educational purposes only and is not financial, investment, or trading advice (NFA). Perpetual futures are leveraged products that carry a high risk of loss, including the loss of your entire margin. Nothing here is a recommendation to buy, sell, or hold any asset. Availability of specific markets may vary by jurisdiction — check the rules that apply to you. Do your own research.*


# How to Trade Perpetuals On-Chain: A Step-by-Step Guide

Learn how to trade perpetual futures on-chain in four steps: connect a self-custody wallet, deposit USDC, choose a market, and open a leveraged position. No account required.

Trading perpetuals on-chain takes four steps: connect a self-custody wallet, deposit USDC as collateral, choose a market, and open a leveraged long or short position. No email, no account, no KYC required at the protocol level — your funds remain in your control throughout. This guide covers each step, what to watch while a trade is open, and the key risks to understand before you start.

> **Not financial advice (NFA).** Perpetual futures are leveraged products that carry a high risk of loss. Availability may vary by jurisdiction.

### What You Need Before You Start

You only need two things to trade perpetuals on-chain:

1. **A self-custody wallet** — a wallet where you hold your own private keys, such as MetaMask, Rabby, or a hardware wallet. This is your on-chain identity; no separate account is created.
2. **USDC** — the stablecoin used as collateral on most on-chain perp platforms. USDC is what you deposit to open positions and what you receive when you close them.

If you're coming from a centralized exchange, withdraw USDC to your self-custody wallet first. If you're new to self-custody wallets, see [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) for background on how on-chain trading differs from a CEX.

### Step 1 — Connect Your Wallet

Navigate to an on-chain perpetuals platform. On [AFX](https://app.afx.xyz/trade), click **"Connect Wallet"** in the top-right corner and select your wallet provider.

Your wallet signs a message to verify ownership — no password is created, no personal data is collected. Once connected, the platform recognizes your wallet address as your account. Every position you open and every dollar of collateral you deposit is tied to that address on-chain.

**What this means in practice:** if you disconnect or switch browsers, your positions don't disappear. Connect the same wallet address from any device and your account state is exactly where you left it.

### Step 2 — Deposit USDC as Collateral

Before opening a trade, you need to deposit USDC into the protocol.

In the trading interface, find the [**Deposit**](https://docs.afx.xyz/deposit) or **Transfer** button and enter the amount of USDC you want to use as margin. You'll be prompted to approve and then confirm a transaction in your wallet — this sends USDC from your wallet to the protocol's smart contract.

A few things to understand at this stage:

* **Your deposited USDC is your total risk capital.** You can only lose what you deposit.
* **Deposits and withdrawals are permissionless.** You can withdraw unused collateral at any time, without waiting for approval.
* **Start small while learning.** You don't need a large amount to begin — small positions let you understand how leverage and funding rates behave before scaling up.

### Step 3 — Choose a Market

Once collateral is deposited, browse the available markets. On AFX, these include:

* **Crypto perpetuals** — [BTC](https://app.afx.xyz/trade/BTCUSDC), [ETH](https://app.afx.xyz/trade/ETHUSDC), [SOL](https://app.afx.xyz/trade/SOLUSDC), and other major tokens
* **Tokenized equity perpetuals** — [MSTR](https://app.afx.xyz/trade/MSTRUSDC), [NVDA](https://app.afx.xyz/trade/NVDAUSDC), [TSLA](https://app.afx.xyz/trade/TSLAUSDC), [AAPL](https://app.afx.xyz/trade/AAPLUSDC) and other stock-linked perps, trading 24/7 with no market-hours restrictions
* **Metal perpetuals** — [XAU](https://app.afx.xyz/trade/XAUUSDC) (gold), [XAG](https://app.afx.xyz/trade/XAGUSDC) (silver), settled in USDC
* **Index perpetuals** — SPX (S\&P 500), giving directional exposure to a broad equity index

Select a market based on what you want exposure to. Each market shows the current **mark price** (used for PnL calculation and liquidation), the **24h change**, and the current **funding rate**.

> On-chain perpetuals don't expire, so you're not choosing a contract month — you're simply opening a position that you can hold for seconds, days, or as long as you choose.

For equity-market exposure, see [How to Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain). It explains how stock perps differ from buying shares.

### Step 4 — Set Your Leverage and Open a Position

This is where you define the actual trade.

#### Long or Short?

* **Long** — you profit if the price rises above your entry
* **Short** — you profit if the price falls below your entry

#### Setting Leverage

Leverage determines how much notional exposure you get per dollar of collateral.

* At **1x leverage**: $100 USDC controls $100 of notional exposure
* At **5x leverage**: $100 USDC controls $500 of notional exposure
* At **10x leverage**: $100 USDC controls $1,000 of notional exposure

Higher leverage amplifies both gains **and losses**, and brings your liquidation price closer to your entry. For beginners, starting at 2x–5x gives meaningful exposure while leaving room for price movement before a liquidation threshold is reached.

#### Market vs Limit Orders

* **Market order**: executes immediately at the best available price. Simple, but you may get slight slippage during fast-moving markets.
* **Limit order**: executes only at the price you specify. Useful when you want to enter at a specific level and are willing to wait.

#### Before You Confirm, Check Three Numbers

1. **Margin required** — the USDC that will be locked as collateral for this position
2. **Liquidation price** — the mark price at which your position would be automatically closed and margin lost
3. **Current funding rate** — the periodic payment between longs and shorts (more on this below)

Once satisfied, confirm the order in your wallet and the position opens.

### Managing an Open Position

#### Funding Rate

A funding rate is a small, periodic payment exchanged between long and short traders — typically every few hours — that keeps the perpetual's price anchored to the spot market.

* If funding is **positive**, longs pay shorts.
* If funding is **negative**, shorts pay longs.

Funding accumulates as long as you hold the position. A high positive funding rate in a strongly bullish market can erode a long position's profits over time. See [What Is a Funding Rate?](/basics/what-is-funding-rate) for a full explanation.

#### Liquidation Price

Your liquidation price is set the moment you open a trade. If the mark price reaches that level, the protocol automatically closes your position and your deposited margin is taken.

You can **raise** your liquidation threshold by adding more collateral to the position (reducing effective leverage), giving the trade more room to breathe. See [What Is Liquidation?](/basics/what-is-liquidation) for more detail.

#### Closing a Position

To close, place an order in the opposite direction of the same size:

* If you're long 0.1 BTC worth of exposure, open a short of 0.1 BTC
* Or use the platform's one-click **Close** button if available

After closing, your realized PnL (profit or loss minus fees and funding paid) is credited back to your collateral balance, which you can withdraw to your wallet at any time.

### Key Risks

Perpetual futures on-chain carry the same directional risks as their centralized equivalents, plus a few that are specific to the on-chain environment:

* **Leverage amplifies losses.** A 10x leveraged position can be liquidated by a 10% adverse price move.
* **Liquidation is permanent.** If your margin is liquidated, it is gone — there is no margin call notice the way a bank would give you.
* **Funding rate drag.** Holding a position in a persistently one-sided market means paying ongoing funding, which erodes returns over time.
* **Smart contract risk.** On-chain protocols depend on smart contracts. While audited platforms reduce this risk, it is never zero. See [AFX's audit reports](https://docs.afx.xyz/audits) for the security reviews covering the bridge contract.
* **Mark price moves.** Your liquidation is based on the mark price (oracle-derived), not the last trade price. In fast markets, the two can diverge briefly.

### Why Trade Perpetuals On-Chain vs a CEX?

On-chain perps add properties that centralized exchanges structurally cannot offer:

|                  | On-Chain Perps                          | CEX Perps                    |
| ---------------- | --------------------------------------- | ---------------------------- |
| **Custody**      | You hold keys until deposit             | Exchange holds your funds    |
| **Account**      | Not required                            | Email + password             |
| **Transparency** | All positions & liquidations on-chain   | Exchange reports only        |
| **Availability** | 24/7 including weekends                 | May have maintenance windows |
| **Asset range**  | Crypto + stock perps + metals + indices | Typically crypto only        |
| **Withdrawal**   | Permissionless, any time                | Subject to platform rules    |

For a deeper comparison, see [On-Chain Perps vs CEX Perps](/basics/on-chain-vs-cex-perps).

### FAQ

**How do you trade perpetuals?** Connect a self-custody wallet to an on-chain perp platform, deposit USDC as margin, select a market, set your leverage and direction (long or short), and submit an order. Your position stays open until you close it or it's liquidated.

**Is perp trading risky?** Yes — particularly with leverage. A leveraged position can lose its entire collateral if the market moves far enough against you. Funding rates can also add ongoing costs to a position held for extended periods. Treat perpetuals as high-risk instruments and only use capital you can afford to lose entirely. (NFA)

**Why trade perps instead of spot?** Perpetuals let you go short (profit when price falls), use leverage to amplify exposure without borrowing tokens, and trade assets like gold or stock-linked perps that have no spot equivalent on-chain. Spot trading only lets you profit when price rises, requires holding the underlying token, and offers no leverage.

**Is $5,000 enough to trade futures on-chain?** Position size requirements depend on the platform and the market, but many on-chain perp platforms have no stated minimum deposit. Smaller amounts are workable at low leverage. That said, the right position size depends on your risk tolerance, leverage level, and how much margin you're comfortable having liquidated — consult a financial professional for advice tailored to your situation. (NFA)

***

### Related guides

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — understand the protocol mechanics behind on-chain perps.
* [How to Trade Stock Perpetuals On-Chain](/how-to-guides/trade-stock-perpetuals-on-chain) — learn how equity perps differ from buying shares.

**Ready to trade?** [Open AFX →](https://app.afx.xyz/trade) *(NFA — perpetual futures carry a high risk of loss. Availability varies by jurisdiction.)*


# How to Trade BTC On-Chain: A Step-by-Step Guide for AFX

Learn how to trade Bitcoin on-chain in 8 steps: deposit USDC on Arbitrum, open a BTC-PERP position on AFX, and withdraw anytime. No CEX, no BTC custody.

**Featured Snippet:** To trade BTC on-chain on AFX, deposit USDC on the Arbitrum network to your AFX account, navigate to the BTC-PERP market, set your leverage and order size, then place a market or limit order. All settlement happens on-chain — your position, margin, and PnL are recorded on the AFX network and withdrawable to your wallet at any time.

### What Does "Trading BTC On-Chain" Mean?

Trading BTC "on-chain" means your trades settle on a blockchain rather than on a centralized exchange's internal ledger. On [AFX](https://www.afx.xyz/), you are trading BTC-PERP — a perpetual futures contract that tracks Bitcoin's price — with settlement on the AFX network and USDC deposits and withdrawals processed over Arbitrum.

This is different from buying Bitcoin on a spot exchange:

* You do not hold or custody actual BTC
* Your margin and profits are denominated in USDC
* Deposits and withdrawals use the Arbitrum blockchain — publicly verifiable
* You can go long or short with leverage up to 100x

On-chain trading means the exchange cannot freeze your funds unilaterally. Deposits and withdrawals are blockchain transactions, not internal ledger entries.

### Before You Start: What You Need

* **A USDC balance on Arbitrum.** AFX only accepts USDC over the Arbitrum network. If your USDC is on Ethereum mainnet or another chain, you will need to bridge it to Arbitrum first using a bridge service.
* **An AFX account.** You can register with an email address or connect a crypto wallet directly.
* **A compatible wallet (optional).** If you use wallet-based login, you need a wallet that supports Arbitrum (e.g., MetaMask with Arbitrum added as a network).

> **Important:** Do not send USDT, ETH, ARB, or any token other than USDC. Do not send USDC on Ethereum mainnet, Solana, or any chain other than Arbitrum. Incorrect deposits are not automatically credited.

### Step-by-Step: How to Trade BTC On-Chain on AFX

#### Step 1 — Create an AFX Account

Go to [app.afx.xyz](https://app.afx.xyz/) and sign up.

* **Email account:** Enter your email, set a password, and verify your email address. AFX creates a custodial account linked to your email.
* **Wallet account:** Click "Connect Wallet," select your wallet, and sign the connection request. Your wallet address becomes your account identifier.

Both account types give you access to the same trading interface and markets.

#### Step 2 — Deposit USDC on Arbitrum

1. Navigate to your **Portfolio** or **Deposit** page inside AFX.
2. Copy your AFX deposit address. This is your Arbitrum address where you will send USDC.
3. From your wallet or exchange, initiate a withdrawal of USDC to this address. Select **Arbitrum** as the network — not Ethereum, not Polygon, not any other chain.
4. Confirm the transaction. Arbitrum transactions typically confirm within seconds to a couple of minutes.
5. Once confirmed, your USDC balance will appear in your AFX account.

If you are withdrawing from a centralized exchange (Binance, Coinbase, Bybit, etc.), look for "Arbitrum" or "ARB" in the network selector when withdrawing USDC.

#### Step 3 — Navigate to the BTC-PERP Market

1. Click on **Trade** in the main navigation.
2. The default market is **BTC-PERP** (BTCUSDC). If you are on a different market, use the market selector at the top of the screen to switch to BTC-PERP.
3. The trading interface shows:
   * A price chart (candlestick, default)
   * The order book (bids and asks in real time)
   * Your open positions and order history at the bottom
   * The order entry panel on the right

#### Step 4 — Set Your Leverage

1. In the order entry panel, find the **leverage slider or input field**.
2. BTC-PERP on AFX supports up to **100x leverage**. For most traders, especially beginners, starting at 2x–5x is more appropriate — higher leverage means your liquidation price is much closer to your entry.
3. Set your desired leverage before placing your order. You can adjust it between trades.

> **How leverage affects your liquidation price:** At 10x leverage, a 10% adverse move exhausts your margin. At 100x, a 1% move can liquidate your position. Always check your estimated liquidation price before confirming.

#### Step 5 — Place Your Order

Choose your order type:

* **Market order:** Executes immediately at the best available price in the order book. Use when you want instant execution and are comfortable with slight slippage.
* **Limit order:** Set the exact price at which you want to buy or sell. The order sits in the book until filled or cancelled. Use when you want price control.
* **Stop order:** Triggers a market order when price reaches a specified level. Use to set stop-losses or breakout entries.

**To go long (buy / profit from price rising):**

1. Select **Buy / Long** in the order panel.
2. Enter your order size (in USDC or BTC units, depending on interface).
3. Review the estimated margin required, liquidation price, and fees.
4. Click **Place Order** (market) or **Place Limit Order**.

**To go short (sell / profit from price falling):**

1. Select **Sell / Short**.
2. Same process as above. A short position gains value when BTC price falls.

#### Step 6 — Monitor Your Position

After your order fills, your open position appears in the **Positions** tab at the bottom of the screen. You can see:

* **Entry price** — the price at which your position was opened
* **Mark price** — the current fair-value price used for PnL and liquidation calculations
* **Unrealized PnL** — your current profit or loss at mark price
* **Liquidation price** — the mark price level at which your position will be force-closed
* **Funding** — the next funding payment direction and rate

Keep the liquidation price visible. If BTC price moves toward it, you can add margin or reduce your position size to avoid liquidation.

#### Step 7 — Close Your Position

When you are ready to exit:

1. In the **Positions** tab, find your open BTC-PERP position.
2. Click **Close** (or **Market Close** for instant execution).
3. Alternatively, place a limit order in the opposite direction to close at a target price.
4. Once closed, your realized PnL is credited to your USDC balance.

To set a take-profit or stop-loss in advance, use a **Stop order** or the platform's TP/SL fields if available in the order panel.

#### Step 8 — Withdraw Your USDC

When you want to move funds back to your wallet:

1. Go to **Portfolio → Withdraw**.
2. Enter the amount and your Arbitrum wallet address.
3. Confirm the withdrawal. AFX processes withdrawals in real time — there is no waiting period or withdrawal queue.
4. The USDC arrives in your Arbitrum wallet, fully on-chain and self-custodied.

### FAQ

#### How to use Bitcoin on-chain?

"Using Bitcoin on-chain" can mean different things. If you want to trade Bitcoin price exposure on-chain, you use a perpetual DEX like AFX — deposit USDC, trade BTC-PERP with leverage, and withdraw USDC back to your wallet. You never hold actual BTC; instead, you hold USDC and take derivative exposure to Bitcoin's price. If you want to transact with actual BTC, you need a Bitcoin wallet and BTC network funds — a different use case from what AFX provides.

#### How to trade BTC on blockchain?

Trading BTC on blockchain means using a DEX that settles trades on-chain rather than on a centralized exchange's private ledger. On AFX, you deposit USDC to an Arbitrum address, trade BTC-PERP through an on-chain orderbook, and withdraw USDC back to your wallet — all transactions are verifiable on the Arbitrum blockchain. The steps are: create account → deposit USDC on Arbitrum → open BTC-PERP position → close position → withdraw USDC.

#### What does BTC on-chain mean?

"On-chain" refers to activity recorded on a blockchain's public ledger. For BTC trading, "on-chain" trading means your margin deposits, withdrawals, and settlement are blockchain transactions — not internal entries on a centralized exchange database. On AFX, the settlement layer is the AFX network, with USDC on Arbitrum used for capital movement. This is distinct from traditional spot Bitcoin transactions on the Bitcoin network itself.

***

### Keep Learning

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — the foundation for understanding how on-chain perp trading works
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the periodic cost (or credit) of holding a leveraged position overnight
* [What Is Liquidation?](/basics/what-is-liquidation) — how forced position closure works and how to avoid it

Ready to trade BTC on-chain? Open a position at [app.afx.xyz](https://app.afx.xyz/trade/BTCUSDC).

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. Trading perpetual futures involves significant risk of loss, including the possibility of losing your entire deposited margin. Not Financial Advice (NFA). Always do your own research and trade only with funds you can afford to lose.*


# Bitcoin vs Gold: Which Is the Better Inflation Hedge?

Gold hit an all-time high in early 2026 while Bitcoin pulled back from its peak. We break down how each asset behaves as an inflation hedge — and how to trade both on-chain.

**Featured Snippet:** Gold and Bitcoin are both described as inflation hedges, but they behave very differently under macro stress. In 2026, gold has risen sharply on central bank buying and geopolitical risk, while Bitcoin has pulled back after peaking in late 2025. Gold tends to outperform during acute fear and rising real yields; Bitcoin tends to outperform when global liquidity expands. Neither is universally "better" — their hedge properties differ by the type of inflation and market environment.

### Why Both Are Called Inflation Hedges

The inflation hedge label gets applied to gold and Bitcoin for related but distinct reasons.

**Gold's case** is built on five thousand years of precedent. It is scarce, durable, accepted globally, and holds no counterparty risk in physical form. Central banks hold gold as a reserve asset precisely because it cannot be debased by monetary policy. When inflation rises and real yields fall, the opportunity cost of holding gold drops — and demand rises. This mechanism has played out consistently across multiple decades.

**Bitcoin's case** is built on algorithmic scarcity. There will never be more than 21 million BTC. Unlike fiat currencies, which can be expanded by central bank policy, Bitcoin's supply schedule is fixed by its protocol and cannot be changed. Proponents argue that Bitcoin is a superior long-run inflation hedge because its scarcity is mathematically verifiable, not geologically dependent.

Both assets share two structural properties: fixed or constrained supply, and low long-run correlation with traditional financial assets like equities and bonds. These properties make each a genuine portfolio diversifier — but the dynamics through which they respond to inflation differ significantly.

### How 2026 Has Tested Both Assets

The macro environment of 2026 has provided a sharp contrast between the two assets in real time.

**Gold** reached a record high of $5,589 per ounce in January 2026, driven by a combination of factors: elevated geopolitical risk, central bank accumulation, and rising inflation forecasts. Central banks have continued buying gold at pace, reflecting a structural shift away from dollar-heavy reserves. In this environment — rising inflation, geopolitical tension, and institutional demand from sovereign buyers — gold has done exactly what it is designed to do.

**Bitcoin** peaked at $126,000 in October 2025 and has pulled back since, trading significantly below that level through the first half of 2026. The pullback reflects a shift in macro conditions: as the risk-off environment intensified and liquidity tightened, Bitcoin was sold alongside other high-beta assets. This is a pattern Bitcoin has shown before — it tends to move with risk appetite, not against it, in the short term.

The divergence in 2026 illustrates the core tension in the "gold vs Bitcoin" debate: gold is a fear asset, while Bitcoin is closer to a liquidity *asset*.

### The Key Structural Differences

#### 1. Volatility Profile

Gold moves in a range that most institutional investors consider manageable. Historically, gold's annualized volatility has been in the 15–20% range — elevated compared to bonds, but modest compared to equities or crypto.

Bitcoin's annualized volatility has historically exceeded 60–80% in active years. This means a position sized identically to a gold holding carries several times the risk exposure. For traders, higher volatility creates more opportunity in both directions. For long-term holders, it requires the tolerance to withstand multi-month drawdowns that would be extraordinary events in gold.

#### 2. What Drives Each Price

| Driver                 | Gold                                                         | Bitcoin                                                                                |
| ---------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------- |
| Real interest rates    | Strong inverse relationship — lower real yields → gold rises | Moderate relationship — affects capital allocation but not the primary driver          |
| Global liquidity (M2)  | Moderate positive                                            | Strong positive — BTC tends to track global liquidity expansion                        |
| Geopolitical risk      | Strong positive — classic safe-haven bid                     | Mixed — can see short-term selling as investors move to cash or gold                   |
| Institutional adoption | Central bank buying, gold ETF flows                          | Spot ETF flows, corporate treasury allocation                                          |
| Supply                 | Geologically constrained; production \~3,500 tonnes/year     | Fixed at 21 million; current supply \~19.8 million, halving cycle reduces new issuance |

#### 3. Behavior in Market Crises

Historical data suggests gold and Bitcoin do not behave the same way during acute market stress.

During sudden risk-off events — market crashes, geopolitical shocks, credit contractions — gold typically receives a safe-haven bid while Bitcoin is often sold alongside equities, as investors move to cash and established safe havens first.

During prolonged inflationary periods with expanding money supply — quantitative easing cycles, fiscal stimulus — Bitcoin has historically outperformed gold significantly, because it benefits more from liquidity-driven speculation and adoption narratives.

This asymmetry matters for how you use each asset. Gold is more reliable as a *defensive* hedge during immediate crises. Bitcoin has historically offered higher returns in *recovery* and *expansion* phases.

#### 4. Correlation to Each Other

Gold and Bitcoin have historically shown low correlation to each other, though this correlation fluctuates. During risk-off selloffs, the correlation tends to drop (gold rises, Bitcoin falls). During bull markets with expanding global liquidity, both can rise simultaneously.

This low average correlation is actually the strongest argument for holding both: they hedge different tail risks.

### Trading Both as Perpetuals: The AFX Angle

The traditional "gold vs Bitcoin" debate is framed around which to *hold* as a long-term store of value. But there is a different question for active traders: which to *trade*, when, and in which direction.

On AFX, both [XAU-PERP](https://app.afx.xyz/trade/XAUUSDC) and [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC) are available in the same account, with the same USDC margin and the same interface. This creates a practical use case that traditional investment frameworks do not address:

**Expressing the macro view directly.** If you believe the current environment — elevated geopolitical risk, rising inflation forecasts, central bank gold buying — favors gold over Bitcoin, you can go long XAU-PERP and short BTC-PERP simultaneously using the same USDC margin. This is a relative value trade expressing the view that gold outperforms BTC in this macro regime, without taking a directional bet on the dollar or on either asset in isolation.

**Switching between assets as macro conditions change.** Liquidity regimes change. The environment in which gold outperforms — fear, tightening, geopolitical stress — is different from the environment in which Bitcoin outperforms — expansion, risk appetite, adoption catalysts. A trader who can move between XAU-PERP and BTC-PERP within a single account, without converting assets or moving funds between venues, has more flexibility to track these regime shifts.

**Trading both with leverage.** XAU-PERP and BTC-PERP are perpetual contracts with no expiry and no rollover. Both support leverage, allowing traders to size positions based on conviction without deploying the full notional value. This is operationally simpler than maintaining a commodity brokerage account for gold futures alongside a crypto exchange for BTC.

### Comparison Table: BTC vs Gold as an Inflation Hedge

<table data-search="false"><thead><tr><th>Dimension</th><th>Gold (XAU)</th><th>Bitcoin (BTC)</th></tr></thead><tbody><tr><td>Type of hedge</td><td>Fear / crisis hedge</td><td>Liquidity / monetary debasement hedge</td></tr><tr><td>Supply constraint</td><td>Geologically limited (~3,500t/yr mined)</td><td>Fixed cap of 21 million coins</td></tr><tr><td>Volatility</td><td>Low–moderate</td><td>High</td></tr><tr><td>Crisis behavior</td><td>Rises during acute risk-off events</td><td>Often sold with equities in short-term panics</td></tr><tr><td>Bull market behavior</td><td>Moderate gains</td><td>High potential upside</td></tr><tr><td>Primary institutional buyer</td><td>Central banks, sovereign funds</td><td>Asset managers, ETFs, corporate treasuries</td></tr><tr><td>Correlation to equities</td><td>Low, often negative during crises</td><td>Moderate positive during risk-on periods</td></tr><tr><td>Available on AFX</td><td>XAU-PERP (perpetual, USDC-margined)</td><td>BTC-PERP (perpetual, USDC-margined, up to 100x)</td></tr></tbody></table>

### FAQ

#### Is gold a better hedge than Bitcoin?

It depends on the type of inflation and market environment. Gold is a more reliable hedge during acute geopolitical crises, sudden risk-off events, and environments where central banks are actively buying. Bitcoin has historically performed better during prolonged monetary expansion and liquidity-driven bull markets. In 2026, gold has significantly outperformed Bitcoin — a macro environment characterized by geopolitical tension and institutional sovereign buying has favored gold's crisis-hedge properties. Neither is universally superior; they hedge different risks.

#### Is it better to hold gold or Bitcoin?

This depends on your risk tolerance and investment horizon. Gold offers lower volatility and a centuries-long track record as a store of value. Bitcoin offers higher potential returns with significantly higher volatility and drawdown risk. Many investors hold both at different portfolio weights — a larger gold allocation for stability and a smaller Bitcoin allocation for asymmetric upside exposure. For traders rather than long-term holders, both are accessible as perpetual contracts on AFX, allowing directional positioning in either asset without holding the underlying.

#### Has Bitcoin outperformed gold?

Over long timeframes, yes — Bitcoin's returns from inception have far exceeded gold's. However, performance over specific windows varies dramatically with market conditions. Gold significantly outperformed Bitcoin in 2022 (when Bitcoin fell over 60%) and has outperformed again through the first half of 2026. Bitcoin significantly outperformed gold during the 2020–2021 expansion and the 2023–2025 recovery cycle. The answer depends entirely on the time window selected.

#### Is there a better hedge than gold?

Gold remains the most institutionally accepted, liquid, and historically consistent inflation hedge across multiple economic regimes. Bitcoin is increasingly discussed as a complementary or alternative hedge, particularly among those focused on long-term monetary debasement. Some argue that Bitcoin's mathematical scarcity makes it structurally superior in the long run; others point to gold's stability and sovereign adoption as arguments for its continuing primacy. No single asset provides perfect hedging across all inflation scenarios — combining assets with different return drivers tends to produce more consistent results than concentrating in one.

***

### Keep Learning

* [How to Trade BTC On-Chain](/how-to-guides/how-to-trade-btc-on-chain) — step-by-step guide to opening a BTC-PERP position on AFX
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the cost of holding a leveraged position in XAU-PERP or BTC-PERP overnight
* [On-Chain Perps vs CEX Perps](/basics/on-chain-vs-cex-perps) — how trading gold and BTC on AFX differs from a centralized exchange

Ready to trade both? Access XAU-PERP and BTC-PERP in one account at [app.afx.xyz](https://app.afx.xyz/).

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. References to historical price performance do not guarantee future results. Trading perpetual futures involves significant risk, including the possibility of losing your entire deposited margin. Not Financial Advice (NFA). Always do your own research.*


# SpaceX Perpetuals on AFX (SPCX): Trade SpaceX On-Chain Without Owning Private Shares

SPCX-PERP on AFX tracks SpaceX's private market valuation. Trade SpaceX exposure on-chain with USDC margin — no accredited investor status, no brokerage required.

**Featured Snippet:** SPCX-PERP is a perpetual futures contract on [AFX](https://app.afx.xyz/trade/SPCXUSDC) that tracks the private market valuation of SpaceX. It is USDC-margined, has no expiry date, and trades 24/7 — giving traders directional exposure to one of the world's most valuable private companies without requiring accredited investor status, a private equity brokerage, or ownership of actual SpaceX shares.

### What Is SPCX-PERP?

SpaceX (Space Exploration Technologies Corp.) is a private aerospace company founded by Elon Musk. As a private company, SpaceX shares are not listed on any public stock exchange. Retail access to SpaceX equity has historically been limited to accredited investors through secondary private market platforms — inaccessible to most traders globally.

SPCX-PERP changes that. It is a perpetual derivatives contract whose oracle price tracks SpaceX's private market reference valuation. You deposit USDC, open a long or short position, and your PnL tracks the movement of SpaceX's reference price — without owning a single share, without accredited investor status, and without using a private equity platform.

The contract is priced using an [**oracle price**](https://docs.afx.xyz/trading-rules/oracle-price) that aggregates SpaceX private market reference data. This oracle is the anchor for mark price calculations, which determine your unrealized PnL and liquidation threshold — not the last traded price in the AFX order book.

### Why Trade SpaceX as an On-Chain Perpetual?

**SpaceX is inaccessible to most investors.** SpaceX has remained private while growing into one of the highest-valued private companies in the world. Secondary market trades in SpaceX shares are restricted to qualified/accredited investors and require navigating platforms that are unavailable in most jurisdictions. SPCX-PERP bypasses this entirely — any trader with a USDC balance and an AFX account can take a position.

**Trade the narrative, long or short.** SpaceX's valuation is driven by high-profile events: Starship test launches, Starlink subscriber growth, NASA and DoD contract announcements, and Elon Musk's public statements. SPCX-PERP lets you express a directional view — long if you believe a milestone event will lift valuation, short if you expect a setback.

**No private market infrastructure.** Buying SpaceX secondary shares requires escrow, legal documentation, transfer agent approval, and significant minimum investment. SPCX-PERP requires a USDC deposit and an order.

**24/7 trading.** Private market SpaceX share transactions are slow and infrequent by nature. SPCX-PERP trades continuously, including overnight and on weekends, allowing you to react to SpaceX news in real time regardless of when it breaks.

**No expiry, no rollover.** SPCX-PERP is a perpetual contract. There is no quarterly settlement, no need to roll into the next contract period, and no delivery of shares. You open a position and close it when you choose.

### How SPCX-PERP Is Priced

**Oracle price.** The oracle aggregates SpaceX private market reference data to produce a fair-value anchor for the contract. This oracle price is displayed alongside the last traded price in the AFX interface. When the two diverge, the funding rate mechanism applies pressure to bring SPCX-PERP back toward the oracle reference.

[**Mark price**](https://docs.afx.xyz/trading-rules/mark-price)**.** The mark price is derived from the oracle and a short-window basis adjustment. Mark price governs your unrealized PnL display and your liquidation threshold — a temporary wick in the SPCX-PERP order book does not move your mark price or trigger liquidation.

[**Funding rate**](https://docs.afx.xyz/trading-rules/funding-rate) **(4-hour cycle).** SPCX-PERP uses a **4-hour funding settlement cycle** — more frequent than the 8-hour standard on most crypto perpetuals. Funding payments flow between longs and shorts every 4 hours. When SPCX-PERP trades at a premium to oracle (bullish sentiment dominates), longs pay shorts. When it trades at a discount, shorts pay longs. The current rate and next settlement countdown are visible in the trading interface.

### Key Specs: SPCX-PERP on AFX

<table data-search="false"><thead><tr><th>Spec</th><th>Detail</th></tr></thead><tbody><tr><td>Contract</td><td>SPCX-PERP (SpaceX private market perpetual)</td></tr><tr><td>Margin currency</td><td>USDC</td></tr><tr><td>Settlement network</td><td>Arbitrum (deposits/withdrawals)</td></tr><tr><td>Trading hours</td><td>24/7, continuous</td></tr><tr><td>Expiry</td><td>None (perpetual)</td></tr><tr><td>Order types</td><td>Market, Limit, Stop</td></tr><tr><td>Funding cycle</td><td>Every 4 hours</td></tr><tr><td>Liquidation basis</td><td>Mark price (oracle-anchored)</td></tr><tr><td>Leverage</td><td>See current interface for leverage tiers</td></tr></tbody></table>

### SPCX-PERP vs Traditional SpaceX Exposure

<table data-search="false"><thead><tr><th>Feature</th><th>SPCX-PERP (AFX)</th><th>SpaceX Secondary Shares</th><th>SpaceX-adjacent Public Stocks</th></tr></thead><tbody><tr><td>Access requirement</td><td>AFX account + USDC</td><td>Accredited investor status</td><td>Standard brokerage account</td></tr><tr><td>Direct SpaceX exposure</td><td>Yes (oracle-tracked)</td><td>Yes (actual equity)</td><td>Indirect only</td></tr><tr><td>Minimum size</td><td>Small (USDC-denominated)</td><td>Often $10,000–$100,000+</td><td>1 share</td></tr><tr><td>Short selling</td><td>Yes, direct</td><td>No (secondary market only)</td><td>Via options/margin</td></tr><tr><td>Settlement speed</td><td>Real-time withdrawal</td><td>Weeks (transfer approval)</td><td>T+1/T+2</td></tr><tr><td>Trading hours</td><td>24/7</td><td>Infrequent, business hours</td><td>Market hours only</td></tr><tr><td>Self-custody</td><td>Yes (wallet-based)</td><td>No</td><td>No</td></tr></tbody></table>

The practical use case for most traders is access and speed: SPCX-PERP provides real-time price exposure to SpaceX's valuation without the institutional infrastructure that private equity participation normally requires.

### Risk Factors Specific to SPCX-PERP

**Private market valuation opacity.** Unlike public companies, SpaceX does not publish quarterly earnings, revenue, or operational data on a regular disclosure schedule. The oracle price derives from private market reference data, which may update less frequently and with less granularity than public equity prices. Valuation can be influenced by infrequent secondary market transactions and analyst estimates rather than continuous market-discovered price.

**Event-driven volatility.** SpaceX's valuation narrative is closely tied to specific events: Starship test outcomes, Starlink revenue disclosures, government contract awards, regulatory approvals, and Elon Musk's public statements. These events can produce sharp price moves in SPCX-PERP when they occur, with no advance notice of timing.

**4-hour funding accumulation.** Because funding settles every 4 hours (6 times per day), the cost of holding a leveraged position in the direction of consensus sentiment accumulates faster than on an 8-hour cycle. In a persistent bull sentiment environment, longs pay 6 funding periods per day.

[**Leverage**](https://docs.afx.xyz/trading-rules/leverage) **and** [**liquidation**](https://docs.afx.xyz/trading-rules/liquidation)**.** SPCX-PERP positions are marked to mark price — oracle-anchored and manipulation-resistant. However, leveraged positions remain subject to liquidation if the oracle price moves sufficiently against your position to exhaust your margin. Always check your estimated liquidation price before entering.

**Liquidity conditions.** SPCX-PERP is a synthetic tracking a private company. Order book depth may be thinner than on major crypto or commodity pairs. During low-activity periods, the bid-ask spread may widen. Use limit orders when precise execution price matters.

### FAQ

#### Do I need to be an accredited investor to trade SPCX-PERP?

No. SPCX-PERP is a perpetual derivatives contract, not a direct purchase of SpaceX equity. You need an AFX account and USDC on Arbitrum — the same requirements as any other AFX pair. The accredited investor restrictions that apply to purchasing actual SpaceX secondary shares do not apply to trading a derivatives contract that tracks SpaceX's reference price.

#### How is SpaceX's private market price determined for the oracle?

The oracle aggregates SpaceX private market reference data from available sources — secondary market transactions, valuation disclosures, and institutional reference data. Because SpaceX is a private company, this data is less continuous and transparent than public equity pricing. The oracle price updates based on available reference data, and the funding rate mechanism keeps [SPCX-PERP](https://app.afx.xyz/trade/SPCXUSDC) anchored to the oracle reference over time.

#### Can I trade SPCX-PERP when SpaceX makes a major announcement?

Yes. SPCX-PERP trades 24/7. If SpaceX makes an announcement outside of traditional market hours — a Starship launch result, a contract win, or a valuation update — you can open or adjust a position immediately. Be aware that significant announcements may cause rapid price moves and that liquidity conditions during off-hours may result in wider spreads.

***

### Keep Learning

* [Bitcoin vs Gold: Which Is the Better Inflation Hedge?](/markets-assets/bitcoin-vs-gold-which-is-the-better-inflation-hedge) — how to think about different asset classes in a portfolio
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — understanding the 4-hour funding cycle on SPCX-PERP

Ready to trade SpaceX on-chain? Open a position at [app.afx.xyz/trade/SPCXUSDC](https://app.afx.xyz/trade/SPCXUSDC).

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. SPCX-PERP is a derivative contract that tracks SpaceX's private market reference price — it does not represent ownership of SpaceX equity or any rights associated with SpaceX shares. Trading perpetual contracts involves significant risk, including the possibility of losing your entire deposited margin. Not Financial Advice (NFA). Always do your own research.*


# Crude Oil Perpetuals (CL-PERP) on AFX: Trade WTI On-Chain 24/7

CL-PERP lets you trade WTI crude oil on-chain with USDC margin, no expiry, and 24/7 access. Learn how crude oil perpetuals work and how to trade them on AFX.

**CL-PERP is a perpetual contract on AFX that tracks the price of WTI crude oil. It settles in USDC, has no expiry date, and trades continuously on-chain — giving you leveraged, two-directional exposure to crude oil without a commodity brokerage account, physical delivery obligations, or monthly contract rollovers.**

### What Are Crude Oil Perpetuals?

A crude oil perpetual is a [perpetual contract](/glossary/perpetual-contract) whose underlying asset is crude oil rather than a cryptocurrency. On AFX the ticker is **CL-PERP** (traded as CLUSDC), and it references **WTI** — West Texas Intermediate, the U.S. benchmark grade.

Like every AFX market, CL-PERP never expires. Traditional crude oil futures on the CME expire every month and must be rolled to keep exposure open. A perpetual removes that mechanic entirely: you open a position, hold it as long as you like, and close it when you choose. A [funding rate](/basics/what-is-funding-rate) keeps the on-chain price tethered to the underlying crude oil reference, so the contract does not need an expiry to stay honest.

### Why Trade Crude Oil On-Chain

Traditional crude oil futures are among the most liquid derivatives in the world, but they are also among the most operationally heavy for retail participants:

* Contracts expire monthly and must be rolled before expiry
* Access requires a futures-enabled brokerage account, often with jurisdiction-specific restrictions
* Margin is typically posted in USD through a bank-linked account
* Trading hours, while extended, are not fully continuous

CL-PERP strips all of that away. If you already hold **USDC**, you can take a macro view on energy markets without touching traditional financial infrastructure:

* **No brokerage account** — an email address or a crypto wallet is enough
* **No rollover** — the position is perpetual
* **Real-time USDC settlement** on Arbitrum, with withdrawals processed on demand
* **24/7 trading**, including weekends and overnight — when many of crude oil's biggest catalysts actually land

For a crypto-native trader, CL-PERP turns oil into just another market on the same screen as [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC) and [gold (XAU-PERP)](https://app.afx.xyz/trade/XAUUSDC).

### How CL-PERP Is Priced

CL-PERP tracks a WTI crude oil **oracle price** aggregated from major reference sources. As with every AFX pair, your unrealized PnL and liquidation level are calculated from the [mark price](/trading-rules/mark-price) — derived from that [oracle price](/glossary/oracle-price) — not from the last traded price in the AFX order book.

This matters because:

* Short-term liquidity gaps in the CL-PERP order book do not spike your mark price
* Liquidation thresholds reflect real crude oil market conditions, not thin on-chain order flow
* During normal conditions, CL-PERP closely tracks front-month WTI futures

#### The 4-hour funding cycle

Crypto perpetuals typically settle funding every 8 hours. **CL-PERP uses a shorter 4-hour funding cycle** — visible on the trading interface as "Funding (4 Hours)" with a live countdown. Funding flows between longs and shorts: when CL-PERP trades at a premium to the reference, longs pay shorts; when it trades at a discount, shorts pay longs. The shorter cycle re-anchors the contract to the underlying more frequently, which suits an asset whose price reacts sharply to scheduled macro events.

### Key Specifications

<table data-search="false"><thead><tr><th>Parameter</th><th>Details</th></tr></thead><tbody><tr><td>Contract</td><td>CL-PERP (WTI crude oil perpetual)</td></tr><tr><td>Symbol</td><td>CLUSDC</td></tr><tr><td>Margin currency</td><td>USDC</td></tr><tr><td>Deposit / withdrawal network</td><td>Arbitrum</td></tr><tr><td>Trading hours</td><td>24/7, continuous</td></tr><tr><td>Expiry</td><td>None (perpetual)</td></tr><tr><td>Funding cycle</td><td>Every 4 hours</td></tr><tr><td>Order types</td><td>Market, limit (with TP / SL)</td></tr><tr><td>Margin modes</td><td>Cross / isolated, One-Way</td></tr><tr><td>Liquidation basis</td><td>Mark price (oracle-anchored)</td></tr><tr><td>Leverage</td><td>See current interface for CL tiers</td></tr></tbody></table>

Leverage tiers and margin requirements for CL-PERP are shown in the trading interface. They differ by market — for reference, BTC-PERP supports up to **100x** — so always confirm the current CL-PERP tier before opening a position. AFX launched CL-PERP on May 11, 2026 alongside BTC-PERP, ETH-PERP, and XAU-PERP as part of its mainnet launch.

### CL-PERP vs Traditional CME Crude Oil Futures

<table data-search="false"><thead><tr><th>Feature</th><th>CL-PERP (AFX)</th><th>CME Crude Oil Futures</th></tr></thead><tbody><tr><td>Expiry</td><td>None (perpetual)</td><td>Monthly, requires rollover</td></tr><tr><td>Account needed</td><td>Email or crypto wallet</td><td>Regulated futures brokerage</td></tr><tr><td>Margin currency</td><td>USDC</td><td>USD (bank-linked)</td></tr><tr><td>Contract size</td><td>Sized for USDC margin; see interface</td><td>1,000 barrels (~$90K notional at $90)</td></tr><tr><td>Settlement</td><td>USDC on-chain</td><td>Cash / physical delivery</td></tr><tr><td>Trading hours</td><td>24/7 continuous</td><td>Extended, with maintenance breaks</td></tr><tr><td>Price anchoring</td><td>Oracle reference + funding rate</td><td>The benchmark itself</td></tr></tbody></table>

The practical takeaway: CME crude is the benchmark, but reaching it requires traditional infrastructure and active roll management. CL-PERP gives you the same directional exposure with USDC, no expiry, and around-the-clock access — at the cost of tracking WTI via an oracle rather than being the settlement instrument itself.

### Risk Factors Specific to Crude Oil

Commodity markets behave differently from crypto. If you are new to energy trading, keep these in mind:

* **Macro and geopolitical shocks.** Conflicts in oil-producing regions, sanctions, and supply-route disruptions can drive rapid, sustained moves — often outside traditional market hours. 24/7 trading lets you react immediately, but moves can also happen while you are away.
* **OPEC+ production decisions.** Scheduled and emergency OPEC+ meetings, and unilateral output changes by major producers, can move crude several percent in minutes.
* **EIA inventory data.** Weekly U.S. EIA petroleum inventory reports are among the most market-moving scheduled releases in commodities; a surprise build or draw can move CL 1–3% within seconds.
* **Supply shocks and demand cycles.** Pipeline outages, refinery fires, Gulf weather, and shifts in global growth expectations create multi-week trends unrelated to crypto narratives.
* **Leverage amplification.** At elevated [leverage](https://docs.afx.xyz/trading-rules/leverage), a 2–3% crude move — routine around macro events — can be a large fraction of your margin. Size positions with discipline and define your maximum loss with a stop before entering.

### FAQ

#### Does CL-PERP ever expire or require rollover?

No. CL-PERP is a perpetual contract with no expiry date. You never roll it to a new contract month — you simply close the position when you want to exit. Removing expiry and rollover is one of the main structural advantages of perpetuals over traditional crude oil futures for retail traders.

#### How often is funding charged on CL-PERP?

Every 4 hours. The trading interface shows the current funding rate and a countdown to the next settlement under "Funding (4 Hours)." If CL-PERP trades above the reference price, longs pay shorts; if it trades below, shorts pay longs.

#### Is the CL-PERP price the same as WTI front-month futures?

Very close during normal conditions. CL-PERP's mark price tracks a WTI oracle reference aggregated from major price sources, so it correlates tightly with CME front-month WTI. Small deviations can occur due to funding basis, but the funding mechanism continuously works to close the gap. You can watch last price, mark price, and oracle price side by side in the AFX interface.

#### Can I go short on crude oil with CL-PERP?

Yes. Like all perpetuals, CL-PERP lets you open a short position to profit from falling crude prices, just as a long position profits from rising prices. This is why perpetuals are useful for both directional views and hedging existing exposure.

### Keep Learning

* [What Is a Perpetual Contract?](/basics/what-is-a-perpetual-dex) — the core instrument behind every AFX market
* [Oracle Price](/glossary/oracle-price) — the external reference that anchors CL-PERP
* [What Is a Funding Rate?](https://argus.cmex.corp/share/basics/what-is-a-funding-rate) — the mechanism behind the 4-hour funding cycle

Ready to trade crude oil on-chain? Open [CL-PERP on AFX](https://app.afx.xyz/trade/CLUSDC) with USDC margin — no brokerage account required.

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. Trading perpetual contracts on commodities involves significant risk, including the possibility of losing your entire deposited margin. Commodity markets can be extremely volatile around macro events. Never trade with funds you cannot afford to lose. Not Financial Advice (NFA). Always do your own research.*


# Apple Stock Perpetuals (AAPL-PERP) on AFX: Trade AAPL On-Chain 24/7

AAPL-PERP lets you trade Apple stock on-chain with USDC margin, no expiry, and 24/7 access. Learn how Apple stock perpetuals work and how to trade them on AFX.

**AAPL-PERP is a perpetual contract on AFX that tracks the price of Apple Inc. (AAPL) stock. It settles in USDC, has no expiry date, and trades 24/7 on-chain — giving you leveraged, two-directional exposure to Apple's share price without a stock brokerage account, without owning the shares, and without waiting for the NASDAQ opening bell.**

### What Is an Apple Stock Perpetual?

An Apple stock perpetual is a [perpetual contract](/glossary/perpetual-contract) whose underlying reference is Apple Inc. (AAPL), the NASDAQ-listed company. On AFX the market is quoted as **AAPLUSDC** (AAPL-PERP), margined in USDC.

You are not buying Apple shares. You hold a derivative that tracks AAPL's price, so you can go **long** if you expect the stock to rise or **short** if you expect it to fall. Like every AFX market, the contract never expires — there is no monthly rollover, and a [funding rate](/basics/what-is-funding-rate) keeps the on-chain price anchored to Apple's reference price instead of an expiry-day settlement.

### Why Trade Apple Stock On-Chain

Buying Apple through a traditional broker works, but it comes with structural constraints that an on-chain perpetual removes:

* **Market hours.** NASDAQ trades roughly 6.5 hours a day, five days a week. AAPL-PERP trades **24/7** — including nights, weekends, and the moments right after Apple reports earnings.
* **Brokerage account.** A traditional stock account requires identity verification tied to a regulated broker, often with jurisdiction limits and funding via bank transfer. On AFX, an email address or a crypto wallet is enough.
* **Long only, for most retail.** Shorting a stock through a broker requires a margin account and share borrow. A perpetual lets you short as easily as you go long.
* **USDC settlement.** If you already hold USDC, you get Apple exposure without converting to fiat or moving funds into a brokerage. Deposits and withdrawals are USDC transactions on Arbitrum, processed in real time.

The clearest advantage is timing. Apple is one of the most-watched stocks in the world, and its biggest moves — earnings, product launches, guidance changes — often break when the stock market is closed. AAPL-PERP lets you act on that information immediately rather than waiting for the next session.

For a crypto-native trader, this turns Apple into just another market on the same screen as [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC), [gold (XAU-PERP)](https://argus.cmex.corp/share/markets-assets/gold-perpetuals-xau), and [SPCX-PERP](https://app.afx.xyz/trade/SPCXUSDC).

### How AAPL-PERP Is Priced

AAPL-PERP tracks an Apple **oracle price** aggregated from market reference data. As with every AFX pair, your unrealized PnL and liquidation level are calculated from the [mark price](https://docs.afx.xyz/trading-rules/mark-price) — derived from that [oracle price](https://docs.afx.xyz/trading-rules/oracle-price) — not from the last traded price in the AFX order book. This protects you from being liquidated by a temporary wick or thin on-chain order flow.

**Funding cycle.** AAPL-PERP settles funding **every 8 hours** — shown on the trading interface as "Funding (8 Hours)" with a live countdown. When AAPL-PERP trades above the reference price, longs pay shorts; when it trades below, shorts pay longs. This ongoing payment is what keeps a no-expiry contract tethered to Apple's actual value.

**A note on closed-market hours.** When NASDAQ is closed, Apple's official last price is static, but AAPL-PERP keeps trading on AFX. During those hours the contract's price reflects live order flow and the oracle's extended reference — which is exactly why the on-chain price can move ahead of the next stock-market open. It also means the gap between the perpetual and the last official close can widen around news, so size positions accordingly.

### Key Specifications

<table data-search="false"><thead><tr><th>Parameter</th><th>Details</th></tr></thead><tbody><tr><td>Contract</td><td>AAPL-PERP (Apple Inc. stock perpetual)</td></tr><tr><td>Symbol</td><td>AAPLUSDC</td></tr><tr><td>Underlying</td><td>Apple Inc. (AAPL), NASDAQ</td></tr><tr><td>Margin currency</td><td>USDC</td></tr><tr><td>Deposit / withdrawal network</td><td>Arbitrum</td></tr><tr><td>Trading hours</td><td>24/7, continuous</td></tr><tr><td>Expiry</td><td>None (perpetual)</td></tr><tr><td>Funding cycle</td><td>Every 8 hours</td></tr><tr><td>Order types</td><td>Market, limit (with TP / SL)</td></tr><tr><td>Margin modes</td><td>Cross / isolated, One-Way</td></tr><tr><td>Liquidation basis</td><td>Mark price (oracle-anchored)</td></tr><tr><td>Leverage</td><td>See current interface for AAPL tiers</td></tr></tbody></table>

Leverage tiers and margin requirements for AAPL-PERP are displayed in the trading interface and may differ from other markets — always confirm the current tier before opening a position. The minimum order size is small (shown in USDC on the order ticket), so you can take a position with a modest amount of margin.

### AAPL-PERP vs Buying Apple Stock

<table data-search="false"><thead><tr><th>Feature</th><th>AAPL-PERP (AFX)</th><th>Apple Shares (Broker)</th></tr></thead><tbody><tr><td>What you hold</td><td>A derivative tracking AAPL's price</td><td>The actual shares</td></tr><tr><td>Account needed</td><td>Email or crypto wallet</td><td>Regulated stock brokerage</td></tr><tr><td>Funding currency</td><td>USDC</td><td>Fiat (bank-linked)</td></tr><tr><td>Trading hours</td><td>24/7 continuous</td><td>NASDAQ hours only</td></tr><tr><td>Direction</td><td>Long or short, natively</td><td>Long easily; short needs margin + borrow</td></tr><tr><td>Leverage</td><td>Available (see interface)</td><td>Limited / requires margin account</td></tr><tr><td>Ownership rights</td><td>None (no voting, no dividends)</td><td>Shareholder rights, dividends</td></tr><tr><td>Settlement</td><td>USDC on-chain</td><td>Share settlement at broker</td></tr></tbody></table>

The trade-off is straightforward: buying shares makes you a part-owner of Apple, with dividends and voting rights, but ties you to market hours and a brokerage. AAPL-PERP gives you round-the-clock, two-directional, USDC-settled exposure to the price — but it is a derivative, not ownership, so you receive no dividends or shareholder rights.

### Risk Factors Specific to Equity Perpetuals

Trading a stock perpetual carries risks that differ from both crypto and traditional share investing:

* **Earnings gaps.** Apple reports quarterly earnings after market close. A surprise can move the stock several percent in seconds. Because AAPL-PERP trades through the release, you can react instantly — but a large gap can also move against a leveraged position faster than you can respond.
* **Overnight and weekend moves.** The underlying stock market is closed much of the week, yet AAPL-PERP keeps trading. News that breaks over a weekend can be priced into the perpetual before the next NASDAQ open, creating gaps versus the last official close.
* **Corporate actions.** Stock splits, dividends, and other corporate events affect the underlying share price. Understand how such events influence AAPL's reference before holding through them.
* **Leverage amplification.** Leverage multiplies both gains and losses. A routine 2–3% equity move, combined with high [leverage](https://docs.afx.xyz/trading-rules/leverage), can represent a large fraction of your margin. Define your maximum loss with a stop before entering.

### FAQ

#### Can I trade Apple stock 24/7 on AFX?

Yes. AAPL-PERP trades continuously, 24 hours a day, seven days a week — unlike Apple shares on NASDAQ, which trade only during market hours on weekdays. This lets you respond to Apple news, such as earnings or product announcements, the moment it breaks rather than waiting for the market to open.

#### Do I own Apple shares when I trade AAPL-PERP?

No. AAPL-PERP is a perpetual contract that tracks Apple's stock price. You do not own the underlying shares, so you receive no dividends and no shareholder voting rights. In exchange, you get leveraged, two-directional exposure settled in USDC, with no brokerage account required.

#### How often is funding charged on AAPL-PERP?

Every 8 hours. The trading interface shows the current funding rate and a countdown to the next settlement under "Funding (8 Hours)." If AAPL-PERP trades above the reference price, longs pay shorts; if it trades below, shorts pay longs.

#### Can I short Apple stock with AAPL-PERP?

Yes. Like all perpetuals, AAPL-PERP lets you open a short position to profit from a falling Apple share price, just as a long position profits from a rising one. There is no share borrow or special margin approval — you simply place a sell order to open a short.

***

### Keep Learning

* [What Is a Perpetual Contract?](/glossary/perpetual-contract) — the core instrument behind every AFX market
* [SPCX Perpetuals (SpaceX)](/markets-assets/spacex-perpetuals-spcx) — trade exposure to a company you can't buy on a normal exchange
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the mechanism behind the 8-hour funding cycle

Ready to trade Apple on-chain? Open [AAPL-PERP on AFX](https://app.afx.xyz/trade/AAPLUSDC) with USDC margin — no brokerage account required.

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice, nor a recommendation to buy or sell any security or derivative. Trading perpetual contracts involves significant risk, including the possibility of losing your entire deposited margin. Equity markets can gap sharply around earnings and news. Never trade with funds you cannot afford to lose. Not Financial Advice (NFA). Always do your own research.*


# SanDisk Stock Perpetuals (SNDK-PERP) on AFX: Trade SNDK On-Chain 24/7

SNDK-PERP lets you trade SanDisk stock on-chain with USDC margin, no expiry, and 24/7 access. Learn how SanDisk stock perpetuals work and how to trade them on AFX.

**SNDK-PERP is a perpetual contract on AFX that tracks the price of SanDisk Corporation (SNDK) stock. It settles in USDC, has no expiry date, and trades 24/7 on-chain — giving you leveraged, two-directional exposure to one of the most volatile names in the memory-chip sector without a stock brokerage account and without owning the shares.**

### What Is a SanDisk Stock Perpetual?

A SanDisk stock perpetual is a [perpetual contract](/glossary/perpetual-contract) whose underlying reference is SanDisk Corporation (SNDK), the NASDAQ-listed company. On AFX the market is quoted as **SNDKUSDC** (SNDK-PERP), margined in USDC.

SanDisk designs and manufactures NAND flash memory and storage products — SSDs, memory cards, and flash storage used in everything from smartphones to AI data centers. It trades as an independent company on NASDAQ after separating from Western Digital in 2025, and it sits in the same competitive set as Micron, Kioxia, SK Hynix, and Samsung. That places SNDK squarely in the semiconductor memory cycle, a sector known for large, fast price swings.

When you trade SNDK-PERP, you are not buying SanDisk shares. You hold a derivative that tracks SNDK's price, so you can go **long** if you expect the stock to rise or **short** if you expect it to fall. Like every AFX market, the contract never expires — there is no monthly rollover, and a [funding rate](/basics/what-is-funding-rate) keeps the on-chain price anchored to SanDisk's reference price instead of relying on an expiry-day settlement.

On AFX, SNDK sits alongside other equity perpetuals such as [AAPL-PERP](https://app.afx.xyz/trade/AAPLUSDC) and [SPCX-PERP](https://app.afx.xyz/trade/SPCXUSDC), plus crypto and commodity markets like [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC) and [gold (XAU-PERP)](https://app.afx.xyz/trade/XAUUSDC) — all margined in the same USDC balance.

### Why Trade SanDisk Stock On-Chain

Buying SanDisk through a traditional broker works, but it comes with structural constraints that an on-chain perpetual removes:

* **Market hours.** NASDAQ trades roughly 6.5 hours a day, five days a week. SNDK-PERP trades **24/7** — including nights, weekends, and the moments right after SanDisk reports earnings or a memory-pricing headline breaks.
* **Brokerage account.** A traditional stock account requires identity verification tied to a regulated broker, often with jurisdiction limits and funding via bank transfer. On AFX, an email address or a crypto wallet is enough to get started.
* **Long only, for most retail.** Shorting a stock through a broker requires a margin account and locating a share borrow. A perpetual lets you short as easily as you go long — you simply place a sell order to open the position. In a sector that whipsaws in both directions, that flexibility matters.
* **USDC settlement.** If you already hold USDC, you get SanDisk exposure without converting to fiat or moving funds into a brokerage. Deposits and withdrawals are USDC transactions on Arbitrum, processed in real time.

The clearest advantage is timing. Memory stocks move hard on catalysts — earnings, NAND pricing data, competitor guidance, and AI-driven demand headlines — and many of those land when the stock market is closed. SNDK-PERP lets you act on that information immediately rather than waiting for the next session.

### Who Trades SanDisk Stock Perpetuals?

Equity perpetuals in a cyclical sector like memory appeal to several kinds of traders:

* **Memory and semiconductor thesis traders.** If you have a view on the NAND/flash cycle — supply gluts, AI-driven demand, pricing recovery — SNDK-PERP is a direct, leverage-capable way to express it, long or short.
* **Event traders.** SanDisk's earnings and sector data releases are scheduled, high-attention catalysts. A 24/7 perpetual lets you position ahead of them and react the instant results drop.
* **Hedgers.** A trader with broader semiconductor or tech exposure can open a short SNDK-PERP position to offset downside risk during an uncertain window, then close it when the risk passes.
* **Crypto-native traders diversifying.** If your capital already lives in USDC, SNDK-PERP lets you add a high-beta equity position without off-ramping to fiat or opening a brokerage account.

In every case the appeal is the same: a familiar underlying with unfamiliar flexibility — leverage, short-selling, and round-the-clock access.

### How SNDK-PERP Is Priced

SNDK-PERP tracks a SanDisk **oracle price** aggregated from market reference data. As with every AFX pair, your unrealized PnL and liquidation level are calculated from the [mark price](https://docs.afx.xyz/trading-rules/mark-price) — derived from that [oracle price](https://docs.afx.xyz/trading-rules/oracle-price) — not from the last traded price in the AFX order book. This protects you from being liquidated by a temporary wick or thin on-chain order flow, which matters especially for a volatile name like SNDK.

**Funding cycle.** SNDK-PERP settles funding **every 8 hours** — shown on the trading interface as "Funding (8 Hours)" with a live countdown. When SNDK-PERP trades above the reference price, longs pay shorts; when it trades below, shorts pay longs. This ongoing payment is what keeps a no-expiry contract tethered to SanDisk's actual value, replacing the role that expiry-day settlement plays in traditional futures.

**A note on closed-market hours.** When NASDAQ is closed, SanDisk's official last price is static, but SNDK-PERP keeps trading on AFX. During those hours the contract's price reflects live order flow and the oracle's extended reference — which is why the on-chain price can move ahead of the next stock-market open. For a stock as volatile as SNDK, the gap between the perpetual and the last official close can widen quickly around news, so size positions with that in mind.

### SanDisk Stock Perpetual Example

Here is how SNDK-PERP works in practice.

Suppose SanDisk's reference price is $1,111 and you expect memory pricing data to push it higher. You open a **long** position with $500 of USDC margin at 5x leverage. That gives you a notional position size of $2,500 — roughly 2.25 shares of SNDK exposure — controlled with $500 of capital.

* **If SNDK rises 8%** to about $1,200, your position gains roughly $200 (a 40% return on your $500 margin, because of the 5x leverage).
* **If SNDK falls 8%** to about $1,022, your position loses roughly $200 — and if the stock keeps falling toward your liquidation price, the position is closed automatically to protect your remaining balance.

An 8% daily move is not unusual for SNDK, which makes the example a useful warning as much as an illustration: leverage on a volatile stock cuts both ways, fast. While the position is open, funding is exchanged every 8 hours. If the funding rate for an interval is +0.01% (positive, meaning the perpetual is trading slightly above reference), a long holder pays 0.01% of the $2,500 notional — about $0.25 — to the short side that interval. If the rate were negative, the long would receive the payment instead.

The same setup works in reverse: expecting SanDisk to fall, you would open a short with a sell order, profiting if the price declines. This two-directional flexibility — plus the absence of any expiry — is the core appeal of an equity perpetual, and leverage is the core risk.

### Key Specifications

<table data-search="false"><thead><tr><th>Parameter</th><th>Details</th></tr></thead><tbody><tr><td>Contract</td><td>SNDK-PERP (SanDisk Corporation stock perpetual)</td></tr><tr><td>Symbol</td><td>SNDKUSDC</td></tr><tr><td>Underlying</td><td>SanDisk Corporation (SNDK), NASDAQ</td></tr><tr><td>Margin currency</td><td>USDC</td></tr><tr><td>Deposit / withdrawal network</td><td>Arbitrum</td></tr><tr><td>Trading hours</td><td>24/7, continuous</td></tr><tr><td>Expiry</td><td>None (perpetual)</td></tr><tr><td>Funding cycle</td><td>Every 8 hours</td></tr><tr><td>Order types</td><td>Market, limit (with TP / SL)</td></tr><tr><td>Margin modes</td><td>Cross / isolated, One-Way</td></tr><tr><td>Liquidation basis</td><td>Mark price (oracle-anchored)</td></tr><tr><td>Leverage</td><td>See current interface for SNDK tiers</td></tr></tbody></table>

Leverage tiers and margin requirements for SNDK-PERP are displayed in the trading interface and may differ from other markets — always confirm the current tier before opening a position. Given SNDK's volatility, using lower leverage is a sensible default. The minimum order size is small (shown in USDC on the order ticket), so you can take a position with a modest amount of margin.

### SNDK-PERP vs Buying SanDisk Stock

<table data-search="false"><thead><tr><th>Feature</th><th>SNDK-PERP (AFX)</th><th>SanDisk Shares (Broker)</th></tr></thead><tbody><tr><td>What you hold</td><td>A derivative tracking SNDK's price</td><td>The actual shares</td></tr><tr><td>Account needed</td><td>Email or crypto wallet</td><td>Regulated stock brokerage</td></tr><tr><td>Funding currency</td><td>USDC</td><td>Fiat (bank-linked)</td></tr><tr><td>Trading hours</td><td>24/7 continuous</td><td>NASDAQ hours only</td></tr><tr><td>Direction</td><td>Long or short, natively</td><td>Long easily; short needs margin + borrow</td></tr><tr><td>Leverage</td><td>Available (see interface)</td><td>Limited / requires margin account</td></tr><tr><td>Ownership rights</td><td>None (no voting, no dividends)</td><td>Shareholder rights</td></tr><tr><td>Settlement</td><td>USDC on-chain</td><td>Share settlement at broker</td></tr></tbody></table>

The trade-off is straightforward: buying shares makes you a part-owner of SanDisk, with voting rights, but ties you to market hours and a brokerage. SNDK-PERP gives you round-the-clock, two-directional, USDC-settled exposure to the price — but it is a derivative, not ownership, so you receive no shareholder rights.

It is also worth distinguishing a stock *perpetual* from a *tokenized stock*. A tokenized stock is a spot token meant to represent a share, held one-for-one; a perpetual is a leveraged derivative that tracks the price and uses a funding rate to stay anchored. SNDK-PERP is the latter — built for active, two-directional trading rather than long-term buy-and-hold ownership.

### How to Trade SNDK-PERP on AFX

1. **Create an account.** Sign in to AFX with an email address or by connecting a crypto wallet — no brokerage onboarding required.
2. **Deposit USDC.** Fund your account with USDC on Arbitrum. This single balance margins every AFX market, including SNDK-PERP.
3. **Open the SNDK-PERP market.** Go to [SNDK-PERP on AFX](https://app.afx.xyz/trade/SNDKUSDC). Check the oracle price, the current funding rate, and the 8-hour countdown at the top of the market header.
4. **Choose your direction and leverage.** Decide long or short, then set your leverage and margin mode (cross or isolated). Because SNDK is volatile, start with conservative leverage — higher leverage moves your liquidation price closer to your entry.
5. **Place the order.** Use a market order for immediate fills or a limit order to set your price. Attach a TP / SL (take-profit / stop-loss) to define your exit levels in advance — essential on a fast-moving stock.
6. **Manage and close.** Monitor your position against the mark price. Because SNDK-PERP never expires, you close whenever you choose — or let your stop or take-profit close it for you.

### Risk Factors Specific to Memory-Sector Equities

Trading a memory-chip stock perpetual carries risks that differ from both crypto and broad-market equities:

* **High volatility.** SanDisk is one of the more volatile large-cap names, with a very wide 52-week trading range. Double-digit single-day moves happen. Combined with leverage, that volatility can erase margin quickly.
* **Sector cyclicality.** NAND flash is a boom-bust market. Supply gluts, capacity expansions, and demand swings (data centers, AI, smartphones, SSDs) drive multi-month trends that can reverse sharply on a single pricing report.
* **Earnings gaps.** SanDisk reports quarterly earnings, typically after market close. A surprise can gap the stock several percent in seconds. SNDK-PERP trades through the release, so you can react instantly — but a large gap can move against a leveraged position faster than you can respond, potentially triggering liquidation.
* **Overnight and weekend moves.** The underlying stock market is closed much of the week, yet SNDK-PERP keeps trading. News breaking over a weekend can be priced into the perpetual before the next NASDAQ open, creating gaps versus the last official close.
* **Corporate actions.** Stock splits, spin-offs, and other corporate events affect the underlying share price. Understand how such events influence SNDK's reference before holding a position through them.
* **Funding cost over time.** If you hold for days or weeks, funding payments accumulate every 8 hours. Factor that ongoing cost into longer holds.
* **Leverage amplification.** Leverage multiplies both gains and losses. On a stock that can move 8% in a day, high [leverage](https://docs.afx.xyz/trading-rules/leverage) can represent a large fraction of your margin. Define your maximum loss with a stop before entering, and size positions conservatively.

### FAQ

#### Can I trade SanDisk stock 24/7 on AFX?

Yes. SNDK-PERP trades continuously, 24 hours a day, seven days a week — unlike SanDisk shares on NASDAQ, which trade only during market hours on weekdays. This lets you respond to SanDisk news, such as earnings or memory-pricing headlines, the moment it breaks rather than waiting for the market to open.

#### Do I own SanDisk shares when I trade SNDK-PERP?

No. SNDK-PERP is a perpetual contract that tracks SanDisk's stock price. You do not own the underlying shares, so you receive no shareholder voting rights. In exchange, you get leveraged, two-directional exposure settled in USDC, with no brokerage account required.

#### What company is SNDK?

SNDK is the NASDAQ ticker for SanDisk Corporation, a maker of NAND flash memory and storage products such as SSDs and memory cards. It trades as an independent company after separating from Western Digital in 2025 and competes with firms like Micron, Kioxia, SK Hynix, and Samsung.

#### Why is SNDK so volatile?

SanDisk operates in the memory-chip sector, which is highly cyclical. NAND flash prices swing with supply and demand — capacity build-outs, data-center and AI demand, and consumer-electronics cycles — so the stock can post large moves in both directions. That volatility is exactly why disciplined position sizing and stop orders matter when trading SNDK-PERP.

#### Can I short SanDisk stock with SNDK-PERP?

Yes. Like all perpetuals, SNDK-PERP lets you open a short position to profit from a falling SanDisk share price, just as a long position profits from a rising one. There is no share borrow or special margin approval — you simply place a sell order to open a short.

#### How much money do I need to start trading SNDK-PERP?

Only enough USDC to meet the minimum order size, which is shown on the order ticket in the AFX interface. Because the contract supports leverage, you can open a position with a modest amount of margin — but remember that higher leverage also increases liquidation risk, especially on a volatile stock, so start conservatively.

***

### Keep Learning

* [What Is a Perpetual Contract?](/glossary/perpetual-contract) — the core instrument behind every AFX market
* [Apple Stock Perpetuals (AAPL-PERP)](/markets-assets/apple-stock-perpetuals-aapl) — another equity perpetual on AFX
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the mechanism behind the 8-hour funding cycle

Ready to trade SanDisk on-chain? Open [SNDK-PERP on AFX](https://app.afx.xyz/trade/SNDKUSDC) with USDC margin — no brokerage account required.

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice, nor a recommendation to buy or sell any security or derivative. Trading perpetual contracts involves significant risk, including the possibility of losing your entire deposited margin. Memory-sector equities can be extremely volatile and can gap sharply around earnings and news. Never trade with funds you cannot afford to lose. Not Financial Advice (NFA). Always do your own research.*


# SK Hynix Stock Perpetuals on AFX: Trade SK Hynix On-Chain 24/7

Trade SK Hynix stock on-chain with USDC margin, no expiry, and 24/7 access. Learn how the SK Hynix perpetual works and how to trade the HBM memory leader on AFX.

**The SK Hynix perpetual (SKHYNIXUSDC) is a contract on AFX that tracks the share price of SK Hynix Inc. — the world's leading supplier of high-bandwidth memory (HBM) for AI. It settles in USDC, has no expiry date, and trades 24/7 on-chain, giving you leveraged, two-directional exposure to a Seoul-listed stock without a Korean brokerage account and without owning the shares.**

### What Is an SK Hynix Stock Perpetual?

An SK Hynix stock perpetual is a [perpetual contract](/basics/what-is-a-perpetual-dex) whose underlying reference is SK Hynix Inc., listed on the Korea Exchange under ticker 000660. On AFX the market is quoted as **SKHYNIXUSDC**, margined in USDC.

SK Hynix is one of the world's largest memory-chip makers. It is a top producer of DRAM and NAND flash, and — most importantly for its recent story — the leading supplier of **HBM (high-bandwidth memory)**, the specialized memory stacked next to AI accelerators like Nvidia's GPUs. That position has put SK Hynix at the center of the AI hardware buildout, and it is a major reason the stock has been one of the most-watched semiconductor names in the world.

When you trade the SK Hynix perpetual, you are not buying SK Hynix shares. You hold a derivative that tracks its price, so you can go **long** if you expect the stock to rise or **short** if you expect it to fall. Like every AFX market, the contract never expires — there is no monthly rollover, and a [funding rate](/basics/what-is-funding-rate) keeps the on-chain price anchored to SK Hynix's reference price instead of relying on an expiry-day settlement.

On AFX, SK Hynix sits alongside other equity perpetuals such as [SanDisk (SNDK-PERP)](https://app.afx.xyz/trade/SNDKUSDC) and [Apple (AAPL-PERP)](https://app.afx.xyz/trade/AAPLUSDC), plus crypto and commodity markets like [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC) — all margined in the same USDC balance.

### Can You Buy SK Hynix Stock Outside Korea?

This is the question most people ask first, and it is where an on-chain perpetual is genuinely useful.

SK Hynix's primary listing is on the **Korea Exchange (KRX: 000660)**, and its shares are priced in Korean won (KRW). It is **not** listed on the NYSE or NASDAQ; US exposure is limited to over-the-counter ADRs. For a retail trader outside South Korea, buying the actual shares usually means opening an international brokerage that supports the Korean market, dealing with currency conversion into KRW, and trading only during Seoul market hours.

The AFX perpetual removes those barriers. It tracks SK Hynix's price in **US-dollar terms** (quoted and settled in USDC), so you get exposure without a Korean brokerage, without converting to won, and without waiting for the Seoul session to open. If you already hold USDC, SK Hynix becomes just another market on your screen.

> **Note on price:** Because SK Hynix shares trade in KRW while the AFX perpetual is quoted in USDC, the number you see on AFX is the SK Hynix price expressed in US dollars — not the raw won figure you would see on a Korean quote page.

### Why Trade SK Hynix On-Chain

Compared with buying the shares through a traditional broker, the SK Hynix perpetual on AFX offers:

* **24/7 trading.** The Korea Exchange trades only during weekday session hours in Korea Standard Time. The SK Hynix perpetual trades **around the clock**, including nights, weekends, and the moments right after memory-pricing or HBM headlines break.
* **No local brokerage.** No Korean or international brokerage onboarding, no KRW conversion. An email address or a crypto wallet is enough to get started.
* **Long or short.** Shorting a foreign stock through a broker is difficult for most retail traders. A perpetual lets you short as easily as you go long — you simply place a sell order.
* **USDC settlement.** Deposits and withdrawals are USDC transactions on Arbitrum, processed in real time. Your single USDC balance margins the position.

The clearest advantage is access plus timing. SK Hynix moves hard on catalysts — earnings, HBM supply agreements, DRAM and NAND pricing data, and competitor guidance — and many of those land far outside Korean market hours. The perpetual lets you act immediately instead of waiting for the next Seoul session.

### Who Trades SK Hynix Perpetuals?

* **AI and memory thesis traders.** If you have a view on the HBM and memory cycle — AI accelerator demand, DRAM/NAND pricing, capacity expansions — the SK Hynix perpetual is a direct, leverage-capable way to express it, long or short.
* **Traders without Korean market access.** For anyone who cannot easily open a Korea-enabled brokerage, the perpetual is a practical way to get SK Hynix price exposure using only USDC.
* **Event traders.** SK Hynix earnings and semiconductor data releases are scheduled, high-attention catalysts. A 24/7 perpetual lets you position ahead of them and react the instant results drop.
* **Hedgers.** A trader with broader semiconductor or AI-hardware exposure can open a short SK Hynix perpetual to offset downside risk during an uncertain window, then close it when the risk passes.

### How the SK Hynix Perpetual Is Priced

SKHYNIXUSDC tracks an SK Hynix **oracle price** aggregated from market reference data and expressed in USD. As with every AFX pair, your unrealized PnL and liquidation level are calculated from the [mark price](https://docs.afx.xyz/trading-rules/mark-price) — derived from that [oracle price](https://docs.afx.xyz/trading-rules/oracle-price) — not from the last traded price in the AFX order book. This protects you from being liquidated by a temporary wick or thin on-chain order flow, which matters for a volatile name like SK Hynix.

**Funding cycle.** The SK Hynix perpetual settles funding **every 8 hours** — shown on the trading interface as "Funding (8 Hours)" with a live countdown. When the perpetual trades above the reference price, longs pay shorts; when it trades below, shorts pay longs. This ongoing payment keeps a no-expiry contract tethered to SK Hynix's actual value, replacing the role that expiry-day settlement plays in traditional futures.

**Closed-market hours.** When the Korea Exchange is closed, SK Hynix's official last price is static, but the perpetual keeps trading on AFX. During those hours the contract's price reflects live order flow and the oracle's extended reference — which is why the on-chain price can move ahead of the next Seoul open. The gap between the perpetual and the last official close can widen quickly around news, so size positions with that in mind.

### SK Hynix Perpetual Example

Here is how the SK Hynix perpetual works in practice.

Suppose SK Hynix's reference price is $1,011 (its price in USD terms) and you expect strong HBM demand to push it higher. You open a **long** position with $500 of USDC margin at 5x leverage. That gives you a notional position size of $2,500 — roughly 2.5 shares of SK Hynix exposure — controlled with $500 of capital.

* **If the price rises 6%** to about $1,072, your position gains roughly $150 (a 30% return on your $500 margin, because of the 5x leverage).
* **If the price falls 6%** to about $950, your position loses roughly $150 — and if it keeps falling toward your liquidation price, the position is closed automatically to protect your remaining balance.

While the position is open, funding is exchanged every 8 hours. If the funding rate for an interval is +0.01% (positive, meaning the perpetual is trading slightly above reference), a long holder pays 0.01% of the $2,500 notional — about $0.25 — to the short side that interval. If the rate were negative, the long would receive the payment instead.

The same setup works in reverse: expecting SK Hynix to fall, you would open a short with a sell order, profiting if the price declines. Two-directional flexibility and no expiry are the appeal; leverage on a volatile stock is the risk.

### Key Specifications

| Parameter                    | Details                         |
| ---------------------------- | ------------------------------- |
| Contract                     | SK Hynix stock perpetual        |
| Symbol                       | SKHYNIXUSDC                     |
| Underlying                   | SK Hynix Inc. (KRX: 000660)     |
| Quote / margin               | USD terms, margined in USDC     |
| Deposit / withdrawal network | Arbitrum                        |
| Trading hours                | 24/7, continuous                |
| Expiry                       | None (perpetual)                |
| Funding cycle                | Every 8 hours                   |
| Order types                  | Market, limit (with TP / SL)    |
| Margin modes                 | Cross / isolated, One-Way       |
| Liquidation basis            | Mark price (oracle-anchored)    |
| Leverage                     | See current interface for tiers |

Leverage tiers and margin requirements are displayed in the trading interface and may differ from other markets — always confirm the current tier before opening a position. Given SK Hynix's volatility, lower leverage is a sensible default. The minimum order size is small (shown in USDC on the order ticket), so you can take a position with a modest amount of margin.

### SK Hynix Perpetual vs Buying the Shares

| Feature          | SK Hynix Perpetual (AFX)        | SK Hynix Shares (Broker)                 |
| ---------------- | ------------------------------- | ---------------------------------------- |
| What you hold    | A derivative tracking the price | The actual shares                        |
| Account needed   | Email or crypto wallet          | Korea-enabled brokerage                  |
| Currency         | USDC (USD terms)                | KRW                                      |
| Trading hours    | 24/7 continuous                 | Korea Exchange hours only                |
| Direction        | Long or short, natively         | Long easily; shorting is hard for retail |
| Leverage         | Available (see interface)       | Limited / margin account needed          |
| Ownership rights | None (no voting, no dividends)  | Shareholder rights                       |
| Settlement       | USDC on-chain                   | Share settlement at broker               |

The trade-off is straightforward: buying shares makes you a part-owner of SK Hynix, with voting rights and any dividends, but ties you to KRW, Korean market hours, and a specialized brokerage. The perpetual gives you round-the-clock, two-directional, USDC-settled exposure to the price — but it is a derivative, not ownership. It is also distinct from a *tokenized stock* (a spot token meant to represent one share); a perpetual is a leveraged derivative that uses a funding rate to stay anchored, built for active trading rather than buy-and-hold.

### How to Trade the SK Hynix Perpetual on AFX

1. **Create an account.** Sign in to AFX with an email address or by connecting a crypto wallet — no brokerage onboarding required.
2. **Deposit USDC.** Fund your account with USDC on Arbitrum. This single balance margins every AFX market, including the SK Hynix perpetual.
3. **Open the market.** Go to [SK Hynix on AFX](https://app.afx.xyz/trade/SKHYNIXUSDC). Check the oracle price, the current funding rate, and the 8-hour countdown at the top of the market header.
4. **Choose direction and leverage.** Decide long or short, then set your leverage and margin mode (cross or isolated). Because SK Hynix is volatile, start with conservative leverage — higher leverage moves your liquidation price closer to your entry.
5. **Place the order.** Use a market order for immediate fills or a limit order to set your price. Attach a TP / SL (take-profit / stop-loss) to define your exit levels in advance.
6. **Manage and close.** Monitor your position against the mark price. Because the perpetual never expires, you close whenever you choose — or let your stop or take-profit close it for you.

### Risk Factors Specific to Memory-Sector Equities

* **High volatility.** SK Hynix is a high-beta memory stock with a very wide 52-week trading range. Double-digit moves happen. Combined with leverage, that volatility can erase margin quickly.
* **Memory-cycle risk.** DRAM, NAND, and HBM are cyclical markets. Supply gluts, capacity expansions, and demand swings drive multi-month trends that can reverse sharply on a single pricing report or competitor announcement.
* **HBM competition.** SK Hynix leads in HBM, but Samsung and Micron are pushing hard. News about qualification wins, yields, or customer allocation can move the stock fast.
* **Earnings and macro gaps.** SK Hynix reports quarterly, and Korea-market and semiconductor macro news can gap the price while the exchange is closed. The perpetual trades through these events, so you can react — but a large gap can move against a leveraged position faster than you can respond.
* **Currency context.** The underlying is priced in KRW; the perpetual is in USD terms. Broad USD/KRW moves are one of several factors reflected in the USD-denominated reference.
* **Funding cost over time.** Holding for days or weeks means funding accrues every 8 hours; factor that into longer holds.
* **Leverage amplification.** Leverage multiplies gains and losses. Define your maximum loss with a stop before entering, and size positions conservatively. See [leverage](https://docs.afx.xyz/trading-rules/leverage) for details.

### FAQ

#### Can I buy SK Hynix stock in the USA?

SK Hynix's primary listing is on the Korea Exchange (ticker 000660), and it is not listed on the NYSE or NASDAQ; US access to the shares is limited to over-the-counter ADRs. On AFX, you can instead trade an SK Hynix perpetual that tracks the price in USD terms, settled in USDC — giving you price exposure without a Korean brokerage or currency conversion. Note this is price exposure via a derivative, not share ownership.

#### Is SK Hynix on the NYSE or NASDAQ?

No. SK Hynix trades on the Korea Exchange in Seoul, priced in Korean won. It is not directly listed on a US exchange. The AFX perpetual is one way to get around-the-clock, USD-denominated exposure to its price.

#### Do I own SK Hynix shares when I trade the perpetual?

No. The SK Hynix perpetual is a contract that tracks SK Hynix's stock price. You do not own the underlying shares, so you receive no shareholder voting rights or dividends. In exchange, you get leveraged, two-directional exposure settled in USDC, with no brokerage account required.

#### Why is SK Hynix stock so volatile?

SK Hynix operates in the memory-chip sector, which is highly cyclical. DRAM, NAND, and HBM prices swing with supply and demand — AI accelerator demand, data-center buildouts, capacity additions, and consumer-electronics cycles — so the stock can post large moves in both directions. That volatility is exactly why disciplined position sizing and stop orders matter when trading the perpetual. This is general context, not a prediction of future price.

#### Can I short SK Hynix with the perpetual?

Yes. Like all perpetuals, the SK Hynix perpetual lets you open a short position to profit from a falling price, just as a long position profits from a rising one. There is no share borrow or special margin approval — you simply place a sell order to open a short.

#### How often is funding charged?

Every 8 hours. The trading interface shows the current funding rate and a countdown to the next settlement under "Funding (8 Hours)." If the perpetual trades above the reference price, longs pay shorts; if it trades below, shorts pay longs.

***

### Keep Learning

* [What Is a Perpetual Contract?](/glossary/perpetual-contract) — the core instrument behind every AFX market
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the mechanism behind the 8-hour funding cycle

Ready to trade SK Hynix on-chain? Open [the SK Hynix perpetual on AFX](https://app.afx.xyz/trade/SKHYNIXUSDC) with USDC margin — no Korean brokerage required.

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice, nor a recommendation to buy or sell any security or derivative. Trading perpetual contracts involves significant risk, including the possibility of losing your entire deposited margin. Memory-sector equities can be extremely volatile and can gap sharply around earnings and news. Never trade with funds you cannot afford to lose. Not Financial Advice (NFA). Always do your own research.*


# What Is an Inflation Hedge? Definition & Examples (2026)

An inflation hedge is an asset that preserves purchasing power when prices rise. Learn how gold and Bitcoin work as inflation hedges and how to trade both on AFX.

**An inflation hedge is an asset whose value tends to rise with — or independently of — consumer price inflation, protecting the holder's purchasing power when the general price level increases.**

### How Inflation Hedges Work

When inflation rises, the real value of cash and fixed-rate bonds falls. A $100 bill buys less in a high-inflation year than it did the year before. Inflation hedges address this by holding value (or gaining value) in the same environment where cash loses it.

Not all inflation hedges work the same way or protect against all types of inflation. The two most widely discussed in 2026 are gold and Bitcoin — and they protect against different inflation dynamics.

### Gold as an Inflation Hedge

Gold's inflation-hedge properties come from two mechanisms:

**Real yield sensitivity.** Gold pays no interest or dividend. When real interest rates are low or negative (i.e., nominal rates minus inflation), the opportunity cost of holding gold drops — investors are giving up little by not holding bonds. This makes gold attractive during inflationary environments where central banks keep nominal rates below the inflation rate.

**Safe-haven demand.** During geopolitical crises or economic instability that accompanies inflation, gold receives a "flight to safety" bid from investors reducing risk exposure. Central banks hold gold as a reserve asset for this reason.

Gold's hedge properties are most reliable during sustained, demand-driven inflation in which real yields compress. It is less effective as a hedge in rapid rate-hike cycles, where rising nominal rates can outpace inflation and make bonds comparatively more attractive.

### Bitcoin as an Inflation Hedge

Bitcoin's inflation-hedge argument is structural rather than historical. The argument rests on:

**Fixed supply.** Only 21 million BTC will ever exist. Unlike fiat currencies, Bitcoin cannot be expanded by central bank policy. Holders argue this makes it a hedge against monetary debasement specifically — the inflation caused by money printing.

**Programmable scarcity.** Bitcoin's supply schedule is written into its protocol. The halving cycle reduces new issuance approximately every four years. This contrasts with gold, whose supply grows each year from mining.

In practice, Bitcoin's behavior as an inflation hedge is more complex. It has significantly outperformed gold over long time horizons, but has shown high correlation to risk assets in the short term — often selling off during acute crises rather than rising like gold does. It behaves more as a *monetary debasement hedge* than a *crisis hedge*.

### Key Differences at a Glance

| Property          | Gold                                          | Bitcoin                                       |
| ----------------- | --------------------------------------------- | --------------------------------------------- |
| Supply constraint | Geologically limited                          | Fixed at 21 million                           |
| Hedge type        | Crisis / fear / real yield                    | Monetary debasement / liquidity               |
| Volatility        | Low–moderate                                  | High                                          |
| Crisis behavior   | Rises during panic                            | Often sold alongside equities                 |
| Track record      | Centuries                                     | \~15 years                                    |
| Tradeable on AFX  | [XAU-PERP](https://app.afx.xyz/trade/XAUUSDC) | [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC) |

### Trading Inflation Hedges on AFX

On AFX, both gold and Bitcoin are available as USDC-margined perpetual contracts — [XAU-PERP](https://app.afx.xyz/trade/XAUUSDC) and [BTC-PERP](https://argus.cmex.corp/share/markets/bitcoin-perpetuals-btc) — in the same account with no expiry and no rollover.

This allows traders to express inflation views directionally: going long the asset they believe will outperform in the current macro regime, going short the one they think will underperform, or holding both simultaneously as a cross-asset position. Neither XAU-PERP nor BTC-PERP requires custody of the underlying asset — positions are USDC-margined and settle on-chain.

### FAQ

#### Is an inflation hedge the same as a safe-haven asset?

Not exactly. Safe-haven assets are bought during fear and market panic — they tend to hold value when equities fall. Inflation hedges are bought when purchasing power is eroding due to rising prices. The two concepts overlap: gold is both a safe haven and an inflation hedge. Bitcoin is more contested as a safe haven but has a stronger structural case as a monetary debasement hedge. The two labels describe related but distinct behaviors.

#### Does holding BTC-PERP or XAU-PERP on AFX act as an inflation hedge?

A long position in BTC-PERP or XAU-PERP gives you price exposure to Bitcoin or gold — the same directional exposure you would have holding the underlying asset. If gold rises due to inflation, a long XAU-PERP position gains. If Bitcoin rises as a monetary debasement hedge, a long BTC-PERP position gains. However, perpetual contracts carry [funding rate](/basics/what-is-funding-rate) costs that accumulate over time, which reduces net returns compared to holding the underlying asset outright for long-term hedging purposes. Perpetuals are better suited for active trading than for multi-year passive hedging.

***

### Keep Learning

* [Bitcoin vs Gold: Which Is the Better Inflation Hedge?](/markets-assets/bitcoin-vs-gold-which-is-the-better-inflation-hedge) — full comparison of both assets across 2026 macro conditions
* [Bitcoin Perpetuals on AFX (BTC-PERP)](/how-to-guides/how-to-trade-btc-on-chain) — BTC-PERP specs, leverage, and risk profile
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the cost of holding a leveraged perpetual position over time

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. Not Financial Advice (NFA).*


# What Is Oracle Price in Crypto? Definition & How It Works

Oracle price is the external reference price fed into a perpetual DEX to anchor contracts to real-world asset values. Learn how it works on AFX for BTC, gold, oil, and SpaceX.

**Oracle price is an externally sourced reference price fed into a smart contract or on-chain trading system to represent the fair value of an asset. On AFX, the oracle price anchors each perpetual contract to its real-world underlying — whether that is Bitcoin, gold, crude oil, or SpaceX's private market valuation — and is used to calculate mark price, which drives PnL and liquidation thresholds.**

### Why Perpetual DEXes Need Oracles

A perpetual contract on a DEX only sees prices from its own order book. If a trader places a large order that moves the SPCX-PERP last traded price by 5%, the contract has no way to know whether that move reflects a real change in SpaceX's valuation or a thin-book manipulation.

The oracle solves this by bringing an external price reference on-chain. Instead of using the last traded price in the AFX book, the protocol derives mark price from the oracle — which aggregates data from multiple external sources and is far harder to manipulate with a single order.

This is especially critical for assets like [XAU-PERP](https://app.afx.xyz/trade/XAUUSDC), [CL-PERP](https://app.afx.xyz/trade/CLUSDC), and [SPCX-PERP](https://app.afx.xyz/trade/SPCXUSDC), where the underlying asset trades in a completely separate market (commodity exchanges, private equity platforms) that has no direct connection to the AFX order book.

### How Oracle Price Works on AFX

On AFX, each perpetual pair displays both a **last traded price** (the most recent fill in the AFX order book) and an **oracle price** (the external reference). You can see both in the trading interface.

The oracle price feeds into the mark price formula:

```
Mark Price ≈ Oracle Price × (1 + Funding Basis)
```

The funding basis is a short-window moving average of the premium or discount between the last traded price and the oracle price. This means:

* If SPCX-PERP is trading at a premium to oracle (buyers pushing the price up), the funding basis is positive, longs pay shorts, and the price is pushed back toward oracle
* If it is trading at a discount, shorts pay longs, and the price is pulled back up

This mechanism keeps each AFX perpetual anchored to its real-world reference without requiring an expiry date.

### Oracle Sources by Asset Type

Different AFX pairs use different types of oracle data, depending on where the underlying asset trades:

| Pair                                            | Underlying               | Oracle Data Source                                |
| ----------------------------------------------- | ------------------------ | ------------------------------------------------- |
| [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC)   | Bitcoin                  | Aggregated spot prices across major crypto venues |
| [ETH-PERP](https://app.afx.xyz/trade/ETHUSDC)   | Ethereum                 | Aggregated spot prices across major crypto venues |
| [XAU-PERP](https://app.afx.xyz/trade/XAUUSDC)   | Gold (XAU/USD)           | Commodity market reference data                   |
| [CL-PERP](https://app.afx.xyz/trade/CLUSDC)     | WTI Crude Oil            | Commodity market reference data                   |
| [SPCX-PERP](https://app.afx.xyz/trade/SPCXUSDC) | SpaceX private valuation | Private market reference data                     |

For crypto pairs (BTC, ETH), the oracle aggregates prices across multiple liquid spot exchanges — making it resistant to manipulation on any single venue. For commodity and private asset pairs, the oracle draws from specialist data sources covering those markets.

### Oracle Price vs Last Traded Price vs Mark Price

These three prices are visible in the AFX interface and each serves a different purpose:

| Price                 | What It Is                                              | Used For                                      |
| --------------------- | ------------------------------------------------------- | --------------------------------------------- |
| **Last Traded Price** | The price of the most recent fill in the AFX order book | Displayed on charts; used for order execution |
| **Oracle Price**      | External reference aggregated from real-world sources   | Anchor for mark price calculation             |
| **Mark Price**        | Oracle price + funding basis adjustment                 | Unrealized PnL display; liquidation threshold |

Your position is **never liquidated based on last traded price**. A temporary wick — a large order that briefly moves the last traded price far from oracle — does not trigger liquidation because mark price stays anchored to oracle.

The gap between last traded price and oracle price tells you the current market sentiment: a positive gap (last > oracle) means buyers are paying a premium and funding will flow from longs to shorts at the next settlement.

### What Happens When Oracle and Market Price Diverge

Persistent divergence between oracle price and last traded price triggers the funding rate mechanism to close the gap over time. If the AFX SPCX-PERP price climbs significantly above the oracle reference — because traders are bullish on SpaceX — longs pay shorts every 4 hours until the price converges back toward oracle.

For large, sudden divergences caused by breaking news (a Starship launch result, a Fed decision affecting gold prices), the oracle update and last traded price may temporarily diverge sharply before converging as market participants absorb the new information.

Traders should monitor the oracle price alongside the last traded price, particularly on non-crypto pairs where the underlying market may be closed (e.g., gold on weekends), causing the oracle to update less frequently while AFX continues trading.

### FAQ

#### Can the oracle price be manipulated?

Oracles aggregate data from multiple external sources, making manipulation significantly harder than manipulating a single order book. Moving the oracle price for a liquid asset like gold or Bitcoin would require moving prices across multiple large external markets simultaneously — an extremely high bar. For private assets like SpaceX, the oracle draws from available private market reference data, which updates less frequently but is not directly controllable by any single AFX participant.

#### Why does my unrealized PnL sometimes differ from what I calculate using the last traded price?

Because unrealized PnL on AFX is calculated using mark price, not last traded price. If the last traded price is temporarily above or below the oracle reference — due to a large order, thin liquidity, or market sentiment — mark price will differ from last traded price. As the two converge (driven by the funding rate mechanism), your displayed unrealized PnL adjusts accordingly.

#### Is the oracle price the same as the index price I see on other platforms?

They serve the same function but may differ in implementation. "Index price" and "oracle price" are often used interchangeably — both refer to an external reference price anchoring the perpetual contract. On AFX, the term "oracle price" is used in the interface. The calculation methodology may vary by platform.

***

### Keep Learning

* [What Is a Funding Rate?](/basics/what-is-funding-rate) — how funding keeps the perpetual price anchored to oracle over time
* [SpaceX Perpetuals on AFX (SPCX)](/markets-assets/spacex-perpetuals-spcx) — oracle pricing for a private-company perpetual

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. Not Financial Advice (NFA).*


# What Is a Perpetual Contract? Definition & How It Works (2026)

A perpetual contract is a derivative that tracks an asset's price with no expiry date. Learn how perpetual futures work, funding rates, and how to trade them on AFX.

**A perpetual contract (or perpetual future) is a derivatives contract that lets you trade the price of an asset with leverage and no expiry date. Unlike traditional futures, it never settles on a fixed date — instead, a funding rate mechanism keeps its price anchored to the underlying asset's spot or reference price, allowing positions to be held indefinitely.**

### Key Takeaways

* A perpetual contract lets you trade an asset's price with leverage and **no expiration date**, so positions can be held indefinitely.
* A **funding rate** — a periodic payment between longs and shorts — keeps the contract price anchored to the underlying's reference price.
* Your PnL and liquidation are calculated on **mark price** (a fair-value oracle reference), not the last traded price.
* Perpetuals let you go **long or short** and use leverage, unlike unleveraged spot trading.
* On [AFX](https://app.afx.xyz/trade/XAUUSDC), every market is a perpetual contract margined in **USDC** and settled **on-chain** on Arbitrum.

### What Is a Perpetual Contract?

A perpetual contract is the most widely traded instrument in crypto derivatives. It gives you exposure to an asset's price movement without requiring you to own the asset itself. You post margin — on AFX, this is always USDC — and open a position that gains or loses value as the underlying price moves.

The defining feature is in the name: it is *perpetual*. Traditional futures contracts expire on a set date (monthly, quarterly), forcing traders to close or roll their positions. A perpetual contract has no expiry. You can hold a position for minutes or months, closing it whenever you choose.

To keep a contract with no expiry anchored to reality, perpetuals rely on the [funding rate](/basics/what-is-funding-rate) — a periodic payment between long and short traders that pulls the contract price back toward the asset's [oracle price](/glossary/oracle-price) whenever the two drift apart.

### How Perpetual Contracts Work

Three mechanisms make a perpetual contract function:

**1. Leverage and margin.** You control a position larger than your deposited capital. A 10x leveraged position requires one-tenth of the notional value as margin. This amplifies both gains and losses — see [Leverage](https://docs.afx.xyz/trading-rules/leverage) for a full breakdown.

**2. Mark price for fair valuation.** Your unrealized profit, loss, and liquidation level are calculated using [mark price](https://docs.afx.xyz/trading-rules/mark-price) — a fair-value price derived from an external oracle reference — not the last traded price in the order book. This protects you from being liquidated by a temporary wick or a manipulated order.

**3. Funding rate to anchor the price.** Because there is no expiry to force convergence with spot, the funding rate does that job continuously. When the perpetual trades above the reference price, longs pay shorts; when it trades below, shorts pay longs. This economic pressure keeps the contract price tethered to the underlying.

### Perpetual Contract Example

Here is how a perpetual contract works in practice, using a BTC-PERP position on AFX.

Suppose BTC is trading at $60,000 and you open a **long** position with $1,000 of USDC margin at 10x leverage. That gives you a notional position size of $10,000 — roughly 0.167 BTC of exposure — controlled with just $1,000 of capital.

* **If BTC rises 5%** to $63,000, your position gains $500 (a 50% return on your $1,000 margin, because of the 10x leverage).
* **If BTC falls 5%** to $57,000, your position loses $500 — and if it keeps falling toward your liquidation price, the position is closed to protect your remaining balance.

While the position is open, funding is settled periodically. If the funding rate for that interval is +0.01% (positive, meaning the perpetual is trading above reference), a long holder pays 0.01% of the $10,000 notional — about $1 — to the short side. If the rate is negative, the long *receives* the payment instead. There is no expiry to worry about: you hold the position until you choose to close it.

This is the core appeal of a perpetual contract — leveraged, two-directional exposure with no rollover — and also its core risk: leverage amplifies losses just as much as gains.

### Perpetual Contract vs Traditional Futures

| Feature           | Perpetual Contract                       | Traditional Futures              |
| ----------------- | ---------------------------------------- | -------------------------------- |
| Expiry date       | None                                     | Fixed (monthly/quarterly)        |
| Rollover required | No                                       | Yes, before each expiry          |
| Price anchoring   | Funding rate mechanism                   | Convergence at settlement        |
| Settlement        | Ongoing (mark-to-market)                 | On expiry date                   |
| Typical use       | Continuous directional exposure, hedging | Delivery, calendar-based hedging |

The absence of expiry is why perpetuals dominate crypto trading volume: traders can express a view and hold it without the operational friction of rolling contracts. On AFX, this extends beyond crypto to commodities and other assets — [crude oil (CL-PERP)](https://app.afx.xyz/trade/CLUSDC) and [gold (XAU-PERP)](https://app.afx.xyz/trade/XAUUSDC) perpetuals let you hold commodity exposure without the quarterly rollover that CME futures require.

### Perpetual Contracts on AFX

On AFX, every market is a perpetual contract, margined in USDC and settled on-chain. This includes:

| Category           | Pairs                                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------------------------- |
| Crypto             | [BTC-PERP](https://app.afx.xyz/trade/BTCUSDC), [ETH-PERP](https://app.afx.xyz/trade/ETHUSDC)                  |
| Commodities        | [XAU-PERP](https://app.afx.xyz/trade/XAUUSDC) (gold), [CL-PERP](https://app.afx.xyz/trade/CLUSDC) (crude oil) |
| Equities / Private | [SPCX-PERP](https://app.afx.xyz/trade/SPCXUSDC) (SpaceX)                                                      |

Every AFX perpetual shares the same mechanics: USDC margin, no expiry, oracle-anchored mark price, market/limit/stop order types, and a funding rate that keeps the contract tethered to its reference. Because AFX is a decentralized exchange, settlement happens on-chain — deposits and withdrawals are USDC transactions on Arbitrum, verifiable on the blockchain.

### FAQ

#### What does perpetual mean in a contract?

"Perpetual" means the contract has no expiration or settlement date. A traditional futures contract expires on a fixed date, after which it is settled and ceases to exist. A perpetual contract never expires — it continues indefinitely, and a funding rate mechanism (rather than an expiry-day settlement) keeps its price aligned with the underlying asset.

#### How long can you hold a perpetual contract?

Indefinitely — there is no time limit. Because a perpetual contract has no expiry date, you can keep a position open for minutes, days, or months, as long as you maintain enough margin to keep it above the maintenance margin level. The main ongoing cost of holding is the funding rate, which is exchanged periodically between longs and shorts.

#### How do you get out of a perpetual contract?

You exit simply by closing the position — placing an opposite order to the one you opened (sell to close a long, or buy to close a short). On AFX you can close manually at any time, or set a stop or take-profit order to close automatically at a target price. Because there is no expiry, closing is entirely at your discretion. A position can also be closed involuntarily through liquidation if your margin falls to the maintenance level.

#### Are perpetuals better than futures?

Neither is strictly "better" — they suit different needs. Perpetual contracts remove the operational friction of expiry and rollover, which is why they dominate crypto trading volume; you can hold a directional view continuously without rolling into a new contract every quarter. Traditional dated futures can be preferable for calendar-based hedging or where physical delivery matters. For continuous, leveraged exposure to crypto, commodities, or other assets, perpetuals are usually the more practical instrument — which is why every market on AFX is a perpetual.

#### What is the difference between a perpetual contract and spot trading?

In spot trading, you buy and own the actual asset — real Bitcoin, real shares. In perpetual contract trading, you never own the underlying; you hold a derivative that tracks its price. Perpetuals allow leverage and let you profit from both rising and falling prices (going long or short), while spot trading is typically unleveraged and only profits when the price rises. On AFX, all trading is via perpetual contracts margined in USDC.

#### Why do perpetual contracts have a funding rate?

Because they have no expiry date to force the contract price to converge with the spot price. Traditional futures naturally converge with spot at settlement. Perpetuals never settle, so the funding rate provides ongoing economic pressure: it pays traders to take the side of the trade that pushes the contract price back toward the reference price. Without funding, a perpetual could drift permanently away from the underlying asset's value.

#### Can I lose more than my margin on a perpetual contract?

On AFX, your maximum loss on a position is limited to the margin allocated to it. When your margin falls to the maintenance margin level (measured against [mark price](https://docs.afx.xyz/trading-rules/mark-price)), the position is liquidated to prevent your balance from going negative. This is why managing leverage and monitoring your [liquidation](/basics/what-is-liquidation) price is critical — higher leverage places your liquidation price closer to your entry.

***

### Keep Learning

* [What Is a Perpetual DEX?](/basics/what-is-a-perpetual-dex) — how perpetual contracts trade on a decentralized, on-chain exchange
* [What Is a Funding Rate?](/basics/what-is-funding-rate) — the mechanism that anchors a perpetual to its reference price

***

*This article is for informational and educational purposes only. It does not constitute financial or investment advice. Trading perpetual contracts involves significant risk, including the possibility of losing your entire deposited margin. Not Financial Advice (NFA). Always do your own research.*


# API Reference

Programmatic interface for perpetual contract trading on the AFX DEX.

AFX DEX uses wallet-signed requests and on-chain settlement for perpetual trading. No API keys required -- all Exchange API requests are authenticated via EIP-712 signatures from Ethereum wallets.

<a href="/pages/WCgkp1vggPjuI3svW0zW" class="button primary">Quick Start — First Trade in 5 Minutes</a>

## Base URLs

| Environment | Exchange API                                  | Info API                               | WebSocket                         |
| ----------- | --------------------------------------------- | -------------------------------------- | --------------------------------- |
| **Mainnet** | `https://api.afx.xyz/api/v1/exchange`         | `https://api.afx.xyz/info/...`         | `wss://ws.afx.xyz/ws/dex`         |
| **Testnet** | `https://api-testnet.afx.xyz/api/v1/exchange` | `https://api-testnet.afx.xyz/info/...` | `wss://ws-testnet.afx.xyz/ws/dex` |

{% hint style="info" %}
Start with the **Testnet** environment. Use `faucetClaim` to get free test funds.
{% endhint %}

## Funding Limits

On mainnet, the minimum deposit is 10 USDC and the minimum withdrawal is 2 USDC.

## API Categories

<table data-view="cards"><thead><tr><th>Title</th><th>Description</th><th data-card-target data-type="content-ref">Target</th></tr></thead><tbody><tr><td><strong>Exchange API</strong></td><td>POST /api/v1/exchange — Place/cancel orders, set leverage, vault management. Requires EIP-712 signature.</td><td><a href="/pages/BuhOTIH4l63pXQfDPXCo">/pages/BuhOTIH4l63pXQfDPXCo</a></td></tr><tr><td><strong>Info API</strong></td><td>GET /info/... — Query account, orders, positions, trades, kline, funding rate. No signature required.</td><td><a href="/pages/uz7Xewliilx3mtOBwGXU">/pages/uz7Xewliilx3mtOBwGXU</a></td></tr><tr><td><strong>WebSocket</strong></td><td>Real-time orderbook, kline, ticker, trades, and account state updates via persistent connection.</td><td><a href="/pages/4YkYRib0XiUqm9hKouPx">/pages/4YkYRib0XiUqm9hKouPx</a></td></tr></tbody></table>

## Authentication

{% columns %}
{% column %}

#### Master Wallet

Controls funds and permissions.

Signs: `approveAgent`, `withdraw`

Domain: `SignTransaction`
{% endcolumn %}

{% column %}

#### Agent Wallet

Authorized by Master for daily trading.

Signs: `placeOrder`, `replaceOrder`, `placeBracketOrder`, `cancelOrder`, `setLeverage`, `setMarginMode`, and other authorized trading operations.

Domain: `Exchange`
{% endcolumn %}
{% endcolumns %}

See [Authentication](/api-reference/signing) for the full EIP-712 signing specification.

### Permission Boundary

| Operation family                                                                                        | Signature                       | Notes                                                                                                                                                                                                  |
| ------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Trading actions such as `placeOrder`, `replaceOrder`, `cancelOrder`, `setLeverage`, and `setMarginMode` | Agent wallet                    | Intended for day-to-day trading automation. These actions can change market risk but cannot withdraw account funds to an external address.                                                             |
| `approveAgent`, `revokeAgent`, account `withdraw`, and testnet `faucetClaim`                            | Master wallet                   | Privileged operations. Keep the Master wallet separate from automated trading infrastructure.                                                                                                          |
| Vault operations                                                                                        | Agent wallet in a vault context | Vault actions can affect vault balances, ownership, withdrawal flow, or closure. Do not assume a vault-authorized Agent is trading-only. Review each vault operation before granting automated access. |

{% hint style="warning" %}
Only the Master wallet can authorize or revoke an Agent wallet. Do not give the Master private key to trading bots or AI agents.
{% endhint %}

See [Agent Safety](/api-reference/agent-safety) for key handling, revocation, rotation, and vault-operation guidance.

## Common Response Format

```json
{
  "code": 0,
  "message": "success",
  "data": { ... }
}
```

<details>

<summary>Error Codes</summary>

| Code    | Description                   |
| ------- | ----------------------------- |
| `0`     | Success                       |
| `40201` | Unsupported action type       |
| `40204` | Signature verification failed |
| `40207` | Invalid nonce                 |
| `40208` | Request expired               |
| `40220` | Rate limit exceeded           |
| `40230` | Blockchain call failed        |
| `40231` | Transaction broadcast failed  |
| `40006` | Location is not supported     |
| `40280` | Action disabled (emergency)   |
| `40281` | Address banned                |

</details>

## Available Symbols

Query `GET /info/public/product-meta` for the canonical product list. Do not hardcode symbol codes or max leverage from examples, because listed markets and risk parameters can change.

Important fields returned by `product-meta`:

| Field                            | Description                                         |
| -------------------------------- | --------------------------------------------------- |
| `code`                           | Numeric product code used by Exchange API requests. |
| `symbol`                         | Product symbol, such as `BTCUSDC`.                  |
| `maxLeverage`                    | Current maximum leverage for the product.           |
| `pricePrecision`, `qtyPrecision` | Display and input precision.                        |
| `tickSize`, `stepSize`           | Minimum price and quantity increments.              |
| `minOrderValue`                  | Minimum order notional.                             |
| `maxSlippagePct`                 | Maximum allowed market-order slippage ratio.        |

## Rate Limits

| Dimension                              | Limit                        |
| -------------------------------------- | ---------------------------- |
| Per address per action                 | Configurable per action type |
| WebSocket connections per IP           | 10                           |
| WebSocket subscriptions per connection | 50                           |
| WebSocket messages per second          | 50                           |


# Quick Start

Place your first trade on AFX DEX in 5 minutes.

{% hint style="info" %}
This guide uses the **Testnet** environment. All operations are free -- use `faucet_claim` to get test funds.
{% endhint %}

## Prerequisites

Two Ethereum wallets are required:

{% columns %}
{% column %}
**Master Wallet**

Controls funds and permissions.

Used to sign `approveAgent` and `withdraw`.
{% endcolumn %}

{% column %}
**Agent Wallet**

Handles day-to-day trading.

Used to sign `placeOrder`, `replaceOrder`, `placeBracketOrder`, `cancelOrder`, `setLeverage`, etc.
{% endcolumn %}
{% endcolumns %}

Store private keys in environment variables. The Python SDK loads keys from the environment and does not accept private keys in public client constructors.

```bash
export AFX_MASTER_PRIVATE_KEY="0xYOUR_MASTER_PRIVATE_KEY"
export AFX_AGENT_PRIVATE_KEY="0xYOUR_AGENT_PRIVATE_KEY"
```

{% hint style="info" %}
On mainnet, the minimum deposit is 10 USDC and the minimum withdrawal is 2 USDC. Testnet examples use faucet funds instead of real deposits.
{% endhint %}

## Install Python SDK

The official Python SDK is maintained in [`afx-dex/afx-python-sdk`](https://github.com/afx-dex/afx-python-sdk). Do not download `dex_client.py`, `dex.proto`, or `dex_pb2.py` from these docs.

```bash
git clone https://github.com/afx-dex/afx-python-sdk.git
cd afx-python-sdk
python3 -m pip install -e .
```

The SDK vendors the generated protobuf module under `afx.protos`, so no manual protobuf compilation is required.

Runnable examples for this flow:

* [faucet\_claim.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/faucet_claim.py)
* [approve\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/approve_agent.py)
* [get\_products.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_products.py)
* [place\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_order.py)
* [replace\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/replace_order.py)
* [place\_bracket\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_bracket_order.py)
* [subscribe\_order\_book.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_order_book.py)

## First Trade

{% stepper %}
{% step %}
**Initialize the client**

```python
from afx import AfxClient

client = AfxClient.from_env(testnet=True)
```

{% endstep %}

{% step %}
**Claim testnet funds**

Get 500 USDC from the testnet faucet. Signed by the **Master** wallet.

```python
result = client.exchange.faucet_claim()
print(result)  # {"code": 0, "message": "success", ...}
```

{% endstep %}

{% step %}
**Authorize the agent wallet**

The Master wallet grants the Agent wallet permission to trade until the authorization expires.

```python
result = client.exchange.approve_agent(
    agent_name="my-bot",
    validity_seconds=604800,
)
print(result)
```

{% endstep %}

{% step %}
**Query available symbols**

```python
products = client.info.get_products()
for p in products["data"]["perpProducts"][:3]:
    print(f"{p['symbol']} (code: {p['code']}, leverage: {p['maxLeverage']}x)")
```

Use the returned `code` value when placing orders. Do not hardcode product codes or leverage values from examples, because markets and risk parameters can change.
{% endstep %}

{% step %}
**Place a limit order**

Signed by the **Agent** wallet. This places a buy order far below market price so it won't fill immediately.

```python
btc = next(p for p in products["data"]["perpProducts"] if p["symbol"] == "BTCUSDC")

result = client.exchange.place_order(
    symbol_code=int(btc["code"]),
    px="50000.0",      # limit price
    qty="0.001",       # quantity in BTC
    side="BUY",
    ord_type="LIMIT",
    tif="GTC",         # Good Till Cancelled
)
print(f"txHash: {result['data']['txHash']}")
```

{% hint style="success" %}
You've placed your first order! The transaction is submitted to the blockchain and confirmed within seconds.
{% endhint %}
{% endstep %}
{% endstepper %}

## Subscribe to Market Data

Connect to real-time orderbook updates via WebSocket.

```python
import asyncio

async def main():
    message = await client.websocket.subscribe_order_book(
        symbol="BTCUSDC",
        depth=5,
        timeout=10,
    )
    book = message["data"]["book"]
    print(f"Best bid: {book['bids'][0]}, Best ask: {book['asks'][0]}")

asyncio.run(main())
```

## What's Next

<table data-view="cards"><thead><tr><th>Title</th><th>Description</th><th data-card-target data-type="content-ref">Target</th></tr></thead><tbody><tr><td><strong>Python SDK</strong></td><td>Install the SDK and run the official examples.</td><td><a href="/pages/gm6l21G4eyGNjnvGjc11">/pages/gm6l21G4eyGNjnvGjc11</a></td></tr><tr><td><strong>Authentication</strong></td><td>How EIP-712 signing works -- Agent vs Master wallet.</td><td><a href="/pages/KD5aN27W1BtKrOW0eFnL">/pages/KD5aN27W1BtKrOW0eFnL</a></td></tr><tr><td><strong>Exchange API</strong></td><td>All trading operations -- orders, leverage, vaults.</td><td><a href="/pages/BuhOTIH4l63pXQfDPXCo">/pages/BuhOTIH4l63pXQfDPXCo</a></td></tr><tr><td><strong>Info API</strong></td><td>Query account, orders, positions, market data.</td><td><a href="/pages/uz7Xewliilx3mtOBwGXU">/pages/uz7Xewliilx3mtOBwGXU</a></td></tr><tr><td><strong>WebSocket</strong></td><td>Real-time orderbook, kline, ticker, and account events.</td><td><a href="/pages/4YkYRib0XiUqm9hKouPx">/pages/4YkYRib0XiUqm9hKouPx</a></td></tr></tbody></table>


# Exchange API

Trading operations — place, replace, bracket, and cancel orders; set leverage; manage vaults.

All trading operations go through a single endpoint:

```
POST /api/v1/exchange
```

The `action.type` field determines which operation to execute. Every request requires an EIP-712 signature. See [Authentication](/api-reference/signing) for signing details.

JavaScript snippets in this section are illustrative pseudocode for action shape and flow. The official high-level SDK examples are currently provided by the Python SDK.

{% hint style="warning" %}
Vault operations can affect vault balances, ownership, withdrawal flow, or lifecycle depending on the action. Do not treat a vault-authorized Agent as trading-only. Review [Agent Safety](/api-reference/agent-safety) before automating vault workflows.
{% endhint %}

## Python SDK Examples

The official SDK repository includes runnable examples for common Exchange actions:

* Orders: [place\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_order.py), [place\_tp\_sl\_orders.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_tp_sl_orders.py), [replace\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/replace_order.py), [place\_bracket\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_bracket_order.py), [cancel\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/cancel_order.py), [cancel\_all.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/cancel_all.py)
* Authorization: [faucet\_claim.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/faucet_claim.py), [approve\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/approve_agent.py), [revoke\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/revoke_agent.py)
* Account settings: [set\_leverage.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/set_leverage.py), [set\_margin\_mode.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/set_margin_mode.py), [assign\_pos\_margin.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/assign_pos_margin.py)
* Funds and vaults: [withdraw.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/withdraw.py), [vault\_deposit.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/vault_deposit.py), [vault\_withdraw.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/vault_withdraw.py), [bind\_referral.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/bind_referral.py)

## Agent Revocation

Use `revoke_agent.py` or `client.exchange.revoke_agent(...)` to revoke the currently approved Agent wallet. The SDK submits an `approveAgent` action with the zero address and `validitySeconds=0`.

Revocation is a **Master wallet** operation. Keep it available in operational runbooks so automated trading access can be disabled quickly.


# Builder Code

Builder Code lets a registered Builder place orders for a Trader after the Trader explicitly authorizes that Builder's agent wallet. The Builder never receives the Trader's private key.

**Integration flow:**

1. The Builder master wallet calls `registerBuilder` once.
2. Each Trader master wallet calls `approveAgentToBuilder` with the Builder agent address and fee cap.
3. The Builder agent calls `placeBuilderOrder` or `placeBuilderBracketOrder` for that Trader.
4. The Trader master wallet calls `revokeAgentToBuilder` to end the authorization.

**Start here:** [Python full lifecycle example](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle example](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts).

Use the SDKs unless you need a raw REST integration. The SDKs create protobuf bytes and EIP-712 signatures for you.

## Register Builder

> Register the Builder master wallet once. Submit \`action.type=registerBuilder\` to \`POST /api/v1/exchange\`.\
> \
> \*\*Signer:\*\* Builder master wallet · \*\*EIP-712 primary type:\*\* \`RegisterBuilder\`\
> \
> \*\*Runnable examples:\*\* \[Python register Builder]\(<https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/register\\_builder.py>) · \[JavaScript register Builder]\(<https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/register-builder.ts)\\>
> \
> \*\*Raw signing.\*\* EIP-712 is a wallet typed-data signature, not a signature of the JSON request string. Sign this exact typed-data payload with the Builder master wallet. Use \`chainId\` \`421614\` for Testnet or \`42161\` for Mainnet; when \`expiryAfter\` is omitted in the request, sign it as \`0\`.\
> \
> \`\`\`json\
> {\
> &#x20; "types": {\
> &#x20;   "EIP712Domain": \[\
> &#x20;     { "name": "name", "type": "string" },\
> &#x20;     { "name": "version", "type": "string" },\
> &#x20;     { "name": "chainId", "type": "uint256" },\
> &#x20;     { "name": "verifyingContract", "type": "address" }\
> &#x20;   ],\
> &#x20;   "RegisterBuilder": \[\
> &#x20;     { "name": "dexChain", "type": "string" },\
> &#x20;     { "name": "name", "type": "string" },\
> &#x20;     { "name": "nonce", "type": "uint64" },\
> &#x20;     { "name": "expiryAfter", "type": "uint64" }\
> &#x20;   ]\
> &#x20; },\
> &#x20; "primaryType": "RegisterBuilder",\
> &#x20; "domain": {\
> &#x20;   "name": "SignTransaction",\
> &#x20;   "version": "1",\
> &#x20;   "chainId": 421614,\
> &#x20;   "verifyingContract": "0x0100000000000000000000000000000000000001"\
> &#x20; },\
> &#x20; "message": {\
> &#x20;   "dexChain": "Testnet",\
> &#x20;   "name": "example-builder",\
> &#x20;   "nonce": 1763023626904,\
> &#x20;   "expiryAfter": 1763023926904\
> &#x20; }\
> }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"tags":[{"name":"Builder Code","description":"Builder Code lets a registered Builder place orders for a Trader after the Trader explicitly authorizes that Builder's agent wallet. The Builder never receives the Trader's private key.\n\n**Integration flow:**\n1. The Builder master wallet calls `registerBuilder` once.\n2. Each Trader master wallet calls `approveAgentToBuilder` with the Builder agent address and fee cap.\n3. The Builder agent calls `placeBuilderOrder` or `placeBuilderBracketOrder` for that Trader.\n4. The Trader master wallet calls `revokeAgentToBuilder` to end the authorization.\n\n**Start here:** [Python full lifecycle example](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle example](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts).\n\nUse the SDKs unless you need a raw REST integration. The SDKs create protobuf bytes and EIP-712 signatures for you.\n"}],"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/exchange/registerBuilder":{"post":{"operationId":"registerBuilder","summary":"Register Builder","tags":["Builder Code"],"description":"Register the Builder master wallet once. Submit `action.type=registerBuilder` to `POST /api/v1/exchange`.\n\n**Signer:** Builder master wallet · **EIP-712 primary type:** `RegisterBuilder`\n\n**Runnable examples:** [Python register Builder](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/register_builder.py) · [JavaScript register Builder](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/register-builder.ts)\n\n**Raw signing.** EIP-712 is a wallet typed-data signature, not a signature of the JSON request string. Sign this exact typed-data payload with the Builder master wallet. Use `chainId` `421614` for Testnet or `42161` for Mainnet; when `expiryAfter` is omitted in the request, sign it as `0`.\n\n```json\n{\n  \"types\": {\n    \"EIP712Domain\": [\n      { \"name\": \"name\", \"type\": \"string\" },\n      { \"name\": \"version\", \"type\": \"string\" },\n      { \"name\": \"chainId\", \"type\": \"uint256\" },\n      { \"name\": \"verifyingContract\", \"type\": \"address\" }\n    ],\n    \"RegisterBuilder\": [\n      { \"name\": \"dexChain\", \"type\": \"string\" },\n      { \"name\": \"name\", \"type\": \"string\" },\n      { \"name\": \"nonce\", \"type\": \"uint64\" },\n      { \"name\": \"expiryAfter\", \"type\": \"uint64\" }\n    ]\n  },\n  \"primaryType\": \"RegisterBuilder\",\n  \"domain\": {\n    \"name\": \"SignTransaction\",\n    \"version\": \"1\",\n    \"chainId\": 421614,\n    \"verifyingContract\": \"0x0100000000000000000000000000000000000001\"\n  },\n  \"message\": {\n    \"dexChain\": \"Testnet\",\n    \"name\": \"example-builder\",\n    \"nonce\": 1763023626904,\n    \"expiryAfter\": 1763023926904\n  }\n}\n```\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegisterBuilderRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/ExchangeOk"}}}}},"components":{"schemas":{"RegisterBuilderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","name","dexChain"],"properties":{"type":{"type":"string","enum":["registerBuilder"]},"name":{"type":"string","minLength":1},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Sign `0` when omitted or null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}},"ExchangeResponse":{"type":"object","properties":{"code":{"type":"integer","description":"`0` = success. See Error Codes section for non-zero values."},"message":{"type":"string"},"data":{"type":"object","nullable":true,"properties":{"txHash":{"type":"string"},"txCode":{"type":"integer"},"txMsg":{"type":"string"}}}}}},"responses":{"ExchangeOk":{"description":"Transaction submitted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExchangeResponse"}}}}}}}
````

## Authorize Builder Agent

> Submit \`action.type=approveAgentToBuilder\` to \`POST /api/v1/exchange\`. The Trader master wallet authorizes the \*\*Builder agent address\*\*, not the Trader's own agent. \`maxFeeRate\` is a positive decimal string and must not exceed the environment-configured Builder fee cap.\
> \
> \*\*Signer:\*\* Trader master wallet · \*\*EIP-712 primary type:\*\* \`ApproveAgentToBuilder\`\
> \
> \*\*Runnable examples:\*\* \[Python full lifecycle]\(<https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder\\_lifecycle.py>) · \[JavaScript approve Builder agent]\(<https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/approve-agent-to-builder.ts)\\>
> \
> \*\*Raw signing.\*\* Sign the following EIP-712 typed-data payload with the Trader master wallet. \`agentAddress\` is the Builder's agent address, \`builderAddress\` is the Builder's master address, and \`expiryAfter\` must be signed as \`0\` when omitted.\
> \
> \`\`\`json\
> {\
> &#x20; "types": {\
> &#x20;   "ApproveAgentToBuilder": \[\
> &#x20;     { "name": "dexChain", "type": "string" },\
> &#x20;     { "name": "agentAddress", "type": "address" },\
> &#x20;     { "name": "builderAddress", "type": "address" },\
> &#x20;     { "name": "maxFeeRate", "type": "string" },\
> &#x20;     { "name": "validitySeconds", "type": "uint64" },\
> &#x20;     { "name": "nonce", "type": "uint64" },\
> &#x20;     { "name": "expiryAfter", "type": "uint64" }\
> &#x20;   ]\
> &#x20; },\
> &#x20; "primaryType": "ApproveAgentToBuilder",\
> &#x20; "domain": { "name": "SignTransaction", "version": "1", "chainId": 421614, "verifyingContract": "0x0100000000000000000000000000000000000001" },\
> &#x20; "message": {\
> &#x20;   "dexChain": "Testnet",\
> &#x20;   "agentAddress": "0x\<builder-agent-address>",\
> &#x20;   "builderAddress": "0x\<builder-master-address>",\
> &#x20;   "maxFeeRate": "0.0002",\
> &#x20;   "validitySeconds": 3600,\
> &#x20;   "nonce": 1763023626904,\
> &#x20;   "expiryAfter": 1763023926904\
> &#x20; }\
> }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"tags":[{"name":"Builder Code","description":"Builder Code lets a registered Builder place orders for a Trader after the Trader explicitly authorizes that Builder's agent wallet. The Builder never receives the Trader's private key.\n\n**Integration flow:**\n1. The Builder master wallet calls `registerBuilder` once.\n2. Each Trader master wallet calls `approveAgentToBuilder` with the Builder agent address and fee cap.\n3. The Builder agent calls `placeBuilderOrder` or `placeBuilderBracketOrder` for that Trader.\n4. The Trader master wallet calls `revokeAgentToBuilder` to end the authorization.\n\n**Start here:** [Python full lifecycle example](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle example](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts).\n\nUse the SDKs unless you need a raw REST integration. The SDKs create protobuf bytes and EIP-712 signatures for you.\n"}],"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/exchange/approveAgentToBuilder":{"post":{"operationId":"approveAgentToBuilder","summary":"Authorize Builder Agent","tags":["Builder Code"],"description":"Submit `action.type=approveAgentToBuilder` to `POST /api/v1/exchange`. The Trader master wallet authorizes the **Builder agent address**, not the Trader's own agent. `maxFeeRate` is a positive decimal string and must not exceed the environment-configured Builder fee cap.\n\n**Signer:** Trader master wallet · **EIP-712 primary type:** `ApproveAgentToBuilder`\n\n**Runnable examples:** [Python full lifecycle](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript approve Builder agent](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/approve-agent-to-builder.ts)\n\n**Raw signing.** Sign the following EIP-712 typed-data payload with the Trader master wallet. `agentAddress` is the Builder's agent address, `builderAddress` is the Builder's master address, and `expiryAfter` must be signed as `0` when omitted.\n\n```json\n{\n  \"types\": {\n    \"ApproveAgentToBuilder\": [\n      { \"name\": \"dexChain\", \"type\": \"string\" },\n      { \"name\": \"agentAddress\", \"type\": \"address\" },\n      { \"name\": \"builderAddress\", \"type\": \"address\" },\n      { \"name\": \"maxFeeRate\", \"type\": \"string\" },\n      { \"name\": \"validitySeconds\", \"type\": \"uint64\" },\n      { \"name\": \"nonce\", \"type\": \"uint64\" },\n      { \"name\": \"expiryAfter\", \"type\": \"uint64\" }\n    ]\n  },\n  \"primaryType\": \"ApproveAgentToBuilder\",\n  \"domain\": { \"name\": \"SignTransaction\", \"version\": \"1\", \"chainId\": 421614, \"verifyingContract\": \"0x0100000000000000000000000000000000000001\" },\n  \"message\": {\n    \"dexChain\": \"Testnet\",\n    \"agentAddress\": \"0x<builder-agent-address>\",\n    \"builderAddress\": \"0x<builder-master-address>\",\n    \"maxFeeRate\": \"0.0002\",\n    \"validitySeconds\": 3600,\n    \"nonce\": 1763023626904,\n    \"expiryAfter\": 1763023926904\n  }\n}\n```\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApproveAgentToBuilderRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/ExchangeOk"}}}}},"components":{"schemas":{"ApproveAgentToBuilderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","agentAddress","builderAddress","maxFeeRate","validitySeconds","dexChain"],"properties":{"type":{"type":"string","enum":["approveAgentToBuilder"]},"agentAddress":{"type":"string","description":"Builder agent address"},"builderAddress":{"type":"string","description":"Builder master wallet address"},"maxFeeRate":{"type":"string","description":"Positive decimal string; subject to the configured fee cap"},"validitySeconds":{"type":"integer","format":"int64","minimum":0},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Sign `0` when omitted or null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}},"ExchangeResponse":{"type":"object","properties":{"code":{"type":"integer","description":"`0` = success. See Error Codes section for non-zero values."},"message":{"type":"string"},"data":{"type":"object","nullable":true,"properties":{"txHash":{"type":"string"},"txCode":{"type":"integer"},"txMsg":{"type":"string"}}}}}},"responses":{"ExchangeOk":{"description":"Transaction submitted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExchangeResponse"}}}}}}}
````

## Revoke Builder Agent Authorization

> Submit \`action.type=revokeAgentToBuilder\` to \`POST /api/v1/exchange\`. The authorization is resolved from the Trader master signature; no Builder or agent address is included in the action.\
> \
> \*\*Signer:\*\* Trader master wallet · \*\*EIP-712 primary type:\*\* \`RevokeAgentToBuilder\`\
> \
> \*\*Runnable examples:\*\* \[Python revoke Builder authorization]\(<https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/revoke\\_agent\\_to\\_builder.py>) · \[JavaScript revoke Builder authorization]\(<https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/revoke-agent-to-builder.ts)\\>
> \
> \*\*Raw signing.\*\* Sign this EIP-712 typed-data payload with the Trader master wallet. The server resolves the Builder and agent from the Trader's active authorization; do not add those addresses to the action.\
> \
> \`\`\`json\
> {\
> &#x20; "types": {\
> &#x20;   "RevokeAgentToBuilder": \[\
> &#x20;     { "name": "dexChain", "type": "string" },\
> &#x20;     { "name": "nonce", "type": "uint64" },\
> &#x20;     { "name": "expiryAfter", "type": "uint64" }\
> &#x20;   ]\
> &#x20; },\
> &#x20; "primaryType": "RevokeAgentToBuilder",\
> &#x20; "domain": { "name": "SignTransaction", "version": "1", "chainId": 421614, "verifyingContract": "0x0100000000000000000000000000000000000001" },\
> &#x20; "message": {\
> &#x20;   "dexChain": "Testnet",\
> &#x20;   "nonce": 1763023626904,\
> &#x20;   "expiryAfter": 1763023926904\
> &#x20; }\
> }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"tags":[{"name":"Builder Code","description":"Builder Code lets a registered Builder place orders for a Trader after the Trader explicitly authorizes that Builder's agent wallet. The Builder never receives the Trader's private key.\n\n**Integration flow:**\n1. The Builder master wallet calls `registerBuilder` once.\n2. Each Trader master wallet calls `approveAgentToBuilder` with the Builder agent address and fee cap.\n3. The Builder agent calls `placeBuilderOrder` or `placeBuilderBracketOrder` for that Trader.\n4. The Trader master wallet calls `revokeAgentToBuilder` to end the authorization.\n\n**Start here:** [Python full lifecycle example](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle example](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts).\n\nUse the SDKs unless you need a raw REST integration. The SDKs create protobuf bytes and EIP-712 signatures for you.\n"}],"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/exchange/revokeAgentToBuilder":{"post":{"operationId":"revokeAgentToBuilder","summary":"Revoke Builder Agent Authorization","tags":["Builder Code"],"description":"Submit `action.type=revokeAgentToBuilder` to `POST /api/v1/exchange`. The authorization is resolved from the Trader master signature; no Builder or agent address is included in the action.\n\n**Signer:** Trader master wallet · **EIP-712 primary type:** `RevokeAgentToBuilder`\n\n**Runnable examples:** [Python revoke Builder authorization](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/revoke_agent_to_builder.py) · [JavaScript revoke Builder authorization](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/revoke-agent-to-builder.ts)\n\n**Raw signing.** Sign this EIP-712 typed-data payload with the Trader master wallet. The server resolves the Builder and agent from the Trader's active authorization; do not add those addresses to the action.\n\n```json\n{\n  \"types\": {\n    \"RevokeAgentToBuilder\": [\n      { \"name\": \"dexChain\", \"type\": \"string\" },\n      { \"name\": \"nonce\", \"type\": \"uint64\" },\n      { \"name\": \"expiryAfter\", \"type\": \"uint64\" }\n    ]\n  },\n  \"primaryType\": \"RevokeAgentToBuilder\",\n  \"domain\": { \"name\": \"SignTransaction\", \"version\": \"1\", \"chainId\": 421614, \"verifyingContract\": \"0x0100000000000000000000000000000000000001\" },\n  \"message\": {\n    \"dexChain\": \"Testnet\",\n    \"nonce\": 1763023626904,\n    \"expiryAfter\": 1763023926904\n  }\n}\n```\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RevokeAgentToBuilderRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/ExchangeOk"}}}}},"components":{"schemas":{"RevokeAgentToBuilderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","dexChain"],"properties":{"type":{"type":"string","enum":["revokeAgentToBuilder"]},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Sign `0` when omitted or null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}},"ExchangeResponse":{"type":"object","properties":{"code":{"type":"integer","description":"`0` = success. See Error Codes section for non-zero values."},"message":{"type":"string"},"data":{"type":"object","nullable":true,"properties":{"txHash":{"type":"string"},"txCode":{"type":"integer"},"txMsg":{"type":"string"}}}}}},"responses":{"ExchangeOk":{"description":"Transaction submitted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExchangeResponse"}}}}}}}
````

## Place Builder Order

> Submit \`action.type=placeBuilderOrder\` to \`POST /api/v1/exchange\` after the Trader authorizes the Builder agent. \`builderFeeRate\` must be a non-negative decimal string and must not exceed the Trader authorization's \`maxFeeRate\`.\
> \
> \*\*Signer:\*\* Builder agent · \*\*Protobuf:\*\* \`MsgPlaceBuilderOrder\`\
> \
> \*\*Runnable examples:\*\* \[Python full lifecycle]\(<https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder\\_lifecycle.py>) · \[JavaScript place Builder order]\(<https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/place-builder-order.ts)\\>
> \
> \*\*Raw signing.\*\* Serialize this message using proto3, then calculate \`connectionId = keccak256(proto\_bytes + bytes(vaultAddress) + little\_endian\_uint64(nonce) + little\_endian\_uint64(expiryAfter))\`. Use empty bytes for an omitted \`vaultAddress\` and \`0\` for an omitted \`expiryAfter\`. The Builder agent then signs this EIP-712 typed-data payload. Use \`source\` \`"b"\` on Testnet or \`"a"\` on Mainnet.\
> \
> \`\`\`json\
> {\
> &#x20; "types": {\
> &#x20;   "Agent": \[\
> &#x20;     { "name": "source", "type": "string" },\
> &#x20;     { "name": "connectionId", "type": "bytes32" }\
> &#x20;   ]\
> &#x20; },\
> &#x20; "primaryType": "Agent",\
> &#x20; "domain": { "name": "Exchange", "version": "1", "chainId": 421614, "verifyingContract": "0x0100000000000000000000000000000000000001" },\
> &#x20; "message": { "source": "b", "connectionId": "0x\<keccak256-result>" }\
> }\
> \`\`\`\
> \
> \`\`\`protobuf\
> message MsgPlaceBuilderOrder {\
> &#x20; int64 cl\_ord\_id = 1;\
> &#x20; int64 symbol\_code = 2;\
> &#x20; string ord\_px = 3;\
> &#x20; string ord\_qty = 4;\
> &#x20; string trigger\_px = 5;\
> &#x20; OrdType ord\_type = 6;\
> &#x20; OrdSide ord\_side = 7;\
> &#x20; OrdTIF time\_in\_force = 8;\
> &#x20; ReduceOnlyOption reduce\_only\_option = 9;\
> &#x20; int64 parent\_ord\_id = 10;\
> &#x20; ConditionalOrdTriggerType tpsl\_trigger\_type = 11;\
> &#x20; string slippage\_pct = 12;\
> &#x20; string builder\_addr = 13;\
> &#x20; string builder\_fee\_rate = 14;\
> }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"tags":[{"name":"Builder Code","description":"Builder Code lets a registered Builder place orders for a Trader after the Trader explicitly authorizes that Builder's agent wallet. The Builder never receives the Trader's private key.\n\n**Integration flow:**\n1. The Builder master wallet calls `registerBuilder` once.\n2. Each Trader master wallet calls `approveAgentToBuilder` with the Builder agent address and fee cap.\n3. The Builder agent calls `placeBuilderOrder` or `placeBuilderBracketOrder` for that Trader.\n4. The Trader master wallet calls `revokeAgentToBuilder` to end the authorization.\n\n**Start here:** [Python full lifecycle example](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle example](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts).\n\nUse the SDKs unless you need a raw REST integration. The SDKs create protobuf bytes and EIP-712 signatures for you.\n"}],"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/exchange/placeBuilderOrder":{"post":{"operationId":"placeBuilderOrder","summary":"Place Builder Order","tags":["Builder Code"],"description":"Submit `action.type=placeBuilderOrder` to `POST /api/v1/exchange` after the Trader authorizes the Builder agent. `builderFeeRate` must be a non-negative decimal string and must not exceed the Trader authorization's `maxFeeRate`.\n\n**Signer:** Builder agent · **Protobuf:** `MsgPlaceBuilderOrder`\n\n**Runnable examples:** [Python full lifecycle](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript place Builder order](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/place-builder-order.ts)\n\n**Raw signing.** Serialize this message using proto3, then calculate `connectionId = keccak256(proto_bytes + bytes(vaultAddress) + little_endian_uint64(nonce) + little_endian_uint64(expiryAfter))`. Use empty bytes for an omitted `vaultAddress` and `0` for an omitted `expiryAfter`. The Builder agent then signs this EIP-712 typed-data payload. Use `source` `\"b\"` on Testnet or `\"a\"` on Mainnet.\n\n```json\n{\n  \"types\": {\n    \"Agent\": [\n      { \"name\": \"source\", \"type\": \"string\" },\n      { \"name\": \"connectionId\", \"type\": \"bytes32\" }\n    ]\n  },\n  \"primaryType\": \"Agent\",\n  \"domain\": { \"name\": \"Exchange\", \"version\": \"1\", \"chainId\": 421614, \"verifyingContract\": \"0x0100000000000000000000000000000000000001\" },\n  \"message\": { \"source\": \"b\", \"connectionId\": \"0x<keccak256-result>\" }\n}\n```\n\n```protobuf\nmessage MsgPlaceBuilderOrder {\n  int64 cl_ord_id = 1;\n  int64 symbol_code = 2;\n  string ord_px = 3;\n  string ord_qty = 4;\n  string trigger_px = 5;\n  OrdType ord_type = 6;\n  OrdSide ord_side = 7;\n  OrdTIF time_in_force = 8;\n  ReduceOnlyOption reduce_only_option = 9;\n  int64 parent_ord_id = 10;\n  ConditionalOrdTriggerType tpsl_trigger_type = 11;\n  string slippage_pct = 12;\n  string builder_addr = 13;\n  string builder_fee_rate = 14;\n}\n```\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PlaceBuilderOrderRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/ExchangeOk"}}}}},"components":{"schemas":{"PlaceBuilderOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","order","builder","builderFeeRate"],"properties":{"type":{"type":"string","enum":["placeBuilderOrder"]},"order":{"$ref":"#/components/schemas/BuilderOrder"},"builder":{"type":"string","description":"Builder master wallet address"},"builderFeeRate":{"type":"string","description":"Non-negative decimal string; must not exceed the Trader authorization"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Use `0` in the L1 connection ID when omitted or null."},"vaultAddress":{"type":"string","nullable":true}}},"BuilderOrder":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit price; use `0` for a market order"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET","STOP_LIMIT","STOP_MARKET","TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"]},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"],"description":"`reduceOnlyOption` is accepted as a compatibility alias."},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}},"ExchangeResponse":{"type":"object","properties":{"code":{"type":"integer","description":"`0` = success. See Error Codes section for non-zero values."},"message":{"type":"string"},"data":{"type":"object","nullable":true,"properties":{"txHash":{"type":"string"},"txCode":{"type":"integer"},"txMsg":{"type":"string"}}}}}},"responses":{"ExchangeOk":{"description":"Transaction submitted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExchangeResponse"}}}}}}}
````

## Place Builder Bracket Order

> Submit 2 or 3 orders with \`action.type=placeBuilderBracketOrder\` to \`POST /api/v1/exchange\`. The first order is the main order; remaining orders must be TP (\`TP\_FROM\_POSITION\`) or SL (\`SL\_FROM\_POSITION\`).\
> \
> \*\*Signer:\*\* Builder agent · \*\*Protobuf:\*\* \`MsgPlaceBuilderBracketOrder\`\
> \
> \*\*Runnable examples:\*\* \[Python full lifecycle]\(<https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder\\_lifecycle.py>) · \[JavaScript full lifecycle]\(<https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts)\\>
> \
> \*\*Raw signing.\*\* Each child order is a \`MsgPlaceBuilderOrder\` with the \`builder\_addr = 13\` and \`builder\_fee\_rate = 14\` fields shown above. Serialize the wrapper below and use the same Builder-agent \`Agent\` EIP-712 signing process as \`placeBuilderOrder\`.\
> \
> \`\`\`protobuf\
> message MsgPlaceBuilderBracketOrder {\
> &#x20; MsgPlaceBuilderOrder main\_order = 1;\
> &#x20; MsgPlaceBuilderOrder take\_profit\_order = 2;\
> &#x20; MsgPlaceBuilderOrder stop\_loss\_order = 3;\
> }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"tags":[{"name":"Builder Code","description":"Builder Code lets a registered Builder place orders for a Trader after the Trader explicitly authorizes that Builder's agent wallet. The Builder never receives the Trader's private key.\n\n**Integration flow:**\n1. The Builder master wallet calls `registerBuilder` once.\n2. Each Trader master wallet calls `approveAgentToBuilder` with the Builder agent address and fee cap.\n3. The Builder agent calls `placeBuilderOrder` or `placeBuilderBracketOrder` for that Trader.\n4. The Trader master wallet calls `revokeAgentToBuilder` to end the authorization.\n\n**Start here:** [Python full lifecycle example](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle example](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts).\n\nUse the SDKs unless you need a raw REST integration. The SDKs create protobuf bytes and EIP-712 signatures for you.\n"}],"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/exchange/placeBuilderBracketOrder":{"post":{"operationId":"placeBuilderBracketOrder","summary":"Place Builder Bracket Order","tags":["Builder Code"],"description":"Submit 2 or 3 orders with `action.type=placeBuilderBracketOrder` to `POST /api/v1/exchange`. The first order is the main order; remaining orders must be TP (`TP_FROM_POSITION`) or SL (`SL_FROM_POSITION`).\n\n**Signer:** Builder agent · **Protobuf:** `MsgPlaceBuilderBracketOrder`\n\n**Runnable examples:** [Python full lifecycle](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/builder_lifecycle.py) · [JavaScript full lifecycle](https://github.com/afx-dex/afx-js-sdk/blob/main/examples/exchange/builder-lifecycle.ts)\n\n**Raw signing.** Each child order is a `MsgPlaceBuilderOrder` with the `builder_addr = 13` and `builder_fee_rate = 14` fields shown above. Serialize the wrapper below and use the same Builder-agent `Agent` EIP-712 signing process as `placeBuilderOrder`.\n\n```protobuf\nmessage MsgPlaceBuilderBracketOrder {\n  MsgPlaceBuilderOrder main_order = 1;\n  MsgPlaceBuilderOrder take_profit_order = 2;\n  MsgPlaceBuilderOrder stop_loss_order = 3;\n}\n```\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PlaceBuilderBracketOrderRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/ExchangeOk"}}}}},"components":{"schemas":{"PlaceBuilderBracketOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","orders","builder","builderFeeRate"],"properties":{"type":{"type":"string","enum":["placeBuilderBracketOrder"]},"orders":{"type":"array","minItems":2,"maxItems":3,"description":"First item is the main order; later items are TP and/or SL orders.","items":{"$ref":"#/components/schemas/BuilderOrder"}},"builder":{"type":"string","description":"Builder master wallet address"},"builderFeeRate":{"type":"string","description":"Non-negative decimal string; must not exceed the Trader authorization"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Use `0` in the L1 connection ID when omitted or null."},"vaultAddress":{"type":"string","nullable":true}}},"BuilderOrder":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit price; use `0` for a market order"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET","STOP_LIMIT","STOP_MARKET","TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"]},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"],"description":"`reduceOnlyOption` is accepted as a compatibility alias."},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}},"ExchangeResponse":{"type":"object","properties":{"code":{"type":"integer","description":"`0` = success. See Error Codes section for non-zero values."},"message":{"type":"string"},"data":{"type":"object","nullable":true,"properties":{"txHash":{"type":"string"},"txCode":{"type":"integer"},"txMsg":{"type":"string"}}}}}},"responses":{"ExchangeOk":{"description":"Transaction submitted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExchangeResponse"}}}}}}}
````


# Models

## The Signature object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The ExchangeResponse object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"ExchangeResponse":{"type":"object","properties":{"code":{"type":"integer","description":"`0` = success. See Error Codes section for non-zero values."},"message":{"type":"string"},"data":{"type":"object","nullable":true,"properties":{"txHash":{"type":"string"},"txCode":{"type":"integer"},"txMsg":{"type":"string"}}}}}}}}
```

## The PlaceOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"PlaceOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","orders"],"properties":{"type":{"type":"string","enum":["placeOrder"]},"orders":{"type":"array","minItems":1,"items":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit `> 0`, Market `\"0\"`"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET"],"description":"NONE and display-only values MARKET_LIQ_SELLOFF, LIMIT_LIQ_SELLOFF, ADL, and LIQUIDATION must not be sent in requests."},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnlyOption":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"]},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}}}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Unix timestamp in milliseconds after which the request expires. null = no expiry; use 0 in the signature payload when this field is null."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The ReplaceOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"ReplaceOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"type":{"type":"string","enum":["replaceOrder"]},"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit `> 0`, Market `\"0\"`"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET"],"description":"NONE and display-only values MARKET_LIQ_SELLOFF, LIMIT_LIQ_SELLOFF, ADL, and LIQUIDATION must not be sent in requests."},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64","description":"Client order ID. clOrdId or ordId is required."},"ordId":{"type":"integer","format":"int64","description":"System order ID. clOrdId or ordId is required."},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"]},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Unix timestamp in milliseconds after which the request expires. null = no expiry; use 0 in the signature payload when this field is null."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The PlaceBracketOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"PlaceBracketOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","orders"],"properties":{"type":{"type":"string","enum":["placeBracketOrder"]},"orders":{"type":"array","minItems":2,"maxItems":3,"items":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit `> 0`, Market `\"0\"`"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET"],"description":"NONE and display-only values MARKET_LIQ_SELLOFF, LIMIT_LIQ_SELLOFF, ADL, and LIQUIDATION must not be sent in requests."},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"]},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}}}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Unix timestamp in milliseconds after which the request expires. null = no expiry; use 0 in the signature payload when this field is null."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The CancelOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"CancelOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","cancels"],"properties":{"type":{"type":"string","enum":["cancelOrder"]},"cancels":{"type":"array","minItems":1,"items":{"type":"object","required":["symbolCode"],"properties":{"symbolCode":{"type":"string"},"clOrdId":{"type":"string","description":"Client order ID (clOrdId or ordId required)"},"ordId":{"type":"string","description":"System order ID (clOrdId or ordId required)"}}}}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The CancelAllRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"CancelAllRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","symbolCode"],"properties":{"type":{"type":"string","enum":["cancelAll"]},"symbolCode":{"type":"integer","format":"int64"},"conditionalOrder":{"type":"boolean","default":false}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The SetLeverageRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"SetLeverageRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","symbolCode","leverage"],"properties":{"type":{"type":"string","enum":["setLeverage"]},"symbolCode":{"type":"integer","format":"int64"},"leverage":{"type":"string","description":">= 1, max 2 decimal places"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The SetMarginModeRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"SetMarginModeRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","symbolCode","marginMode"],"properties":{"type":{"type":"string","enum":["setMarginMode"]},"symbolCode":{"type":"integer","format":"int64"},"marginMode":{"type":"string","enum":["CROSS","ISOLATED"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The AssignPosMarginRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"AssignPosMarginRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","symbolCode","assignedPosMargin"],"properties":{"type":{"type":"string","enum":["assignPosMargin"]},"symbolCode":{"type":"integer","format":"int64"},"assignedPosMargin":{"type":"string","description":"Amount to assign (non-zero)"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"vaultAddress":{"type":"string","nullable":true}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The ApproveAgentRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"ApproveAgentRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","agentAddress","agentName","validitySeconds","dexChain"],"properties":{"type":{"type":"string","enum":["approveAgent"]},"agentAddress":{"type":"string","description":"Agent wallet address (0x hex)"},"agentName":{"type":"string","default":"app.afx.xyz","description":"Agent name. SDK default: app.afx.xyz"},"validitySeconds":{"type":"integer","format":"int64","description":"Agent authorization duration in seconds. 0 means the authorization is valid for 7 days; maximum 365 days."},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]},"referralCode":{"type":"string","description":"Referral code (only effective on first approve)"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Unix timestamp in milliseconds after which the request expires. null = no expiry; use 0 in the signature payload when this field is null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The WithdrawRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"WithdrawRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","destination","amount"],"properties":{"type":{"type":"string","enum":["withdraw"]},"destination":{"type":"string","description":"Recipient address (0x hex)"},"amount":{"type":"string","description":"Withdrawal amount. Minimum mainnet withdrawal: 2 USDC."}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Unix timestamp in milliseconds after which the request expires. For withdrawals, use a longer window such as current time + 3,600,000 milliseconds. null = no expiry; use 0 in the signature payload when this field is null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The BindReferralRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"BindReferralRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","referralCode"],"properties":{"type":{"type":"string","enum":["bindReferral"]},"referralCode":{"type":"string"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64","description":"Request nonce as a Unix timestamp in milliseconds. Recommended: current time in milliseconds. Must be unique; do not reuse the same nonce for another signed request."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The BuilderOrder object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"BuilderOrder":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit price; use `0` for a market order"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET","STOP_LIMIT","STOP_MARKET","TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"]},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"],"description":"`reduceOnlyOption` is accepted as a compatibility alias."},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}}}}}
```

## The RegisterBuilderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"RegisterBuilderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","name","dexChain"],"properties":{"type":{"type":"string","enum":["registerBuilder"]},"name":{"type":"string","minLength":1},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Sign `0` when omitted or null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The ApproveAgentToBuilderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"ApproveAgentToBuilderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","agentAddress","builderAddress","maxFeeRate","validitySeconds","dexChain"],"properties":{"type":{"type":"string","enum":["approveAgentToBuilder"]},"agentAddress":{"type":"string","description":"Builder agent address"},"builderAddress":{"type":"string","description":"Builder master wallet address"},"maxFeeRate":{"type":"string","description":"Positive decimal string; subject to the configured fee cap"},"validitySeconds":{"type":"integer","format":"int64","minimum":0},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Sign `0` when omitted or null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The RevokeAgentToBuilderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"RevokeAgentToBuilderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","dexChain"],"properties":{"type":{"type":"string","enum":["revokeAgentToBuilder"]},"dexChain":{"type":"string","enum":["Mainnet","Testnet"]}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Sign `0` when omitted or null."}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The PlaceBuilderOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"PlaceBuilderOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","order","builder","builderFeeRate"],"properties":{"type":{"type":"string","enum":["placeBuilderOrder"]},"order":{"$ref":"#/components/schemas/BuilderOrder"},"builder":{"type":"string","description":"Builder master wallet address"},"builderFeeRate":{"type":"string","description":"Non-negative decimal string; must not exceed the Trader authorization"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Use `0` in the L1 connection ID when omitted or null."},"vaultAddress":{"type":"string","nullable":true}}},"BuilderOrder":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit price; use `0` for a market order"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET","STOP_LIMIT","STOP_MARKET","TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"]},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"],"description":"`reduceOnlyOption` is accepted as a compatibility alias."},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```

## The PlaceBuilderBracketOrderRequest object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Exchange API","version":"1.0.0"},"components":{"schemas":{"PlaceBuilderBracketOrderRequest":{"type":"object","required":["action","signature","nonce"],"properties":{"action":{"type":"object","required":["type","orders","builder","builderFeeRate"],"properties":{"type":{"type":"string","enum":["placeBuilderBracketOrder"]},"orders":{"type":"array","minItems":2,"maxItems":3,"description":"First item is the main order; later items are TP and/or SL orders.","items":{"$ref":"#/components/schemas/BuilderOrder"}},"builder":{"type":"string","description":"Builder master wallet address"},"builderFeeRate":{"type":"string","description":"Non-negative decimal string; must not exceed the Trader authorization"}}},"signature":{"$ref":"#/components/schemas/Signature"},"nonce":{"type":"integer","format":"int64"},"expiryAfter":{"type":"integer","format":"int64","nullable":true,"description":"Use `0` in the L1 connection ID when omitted or null."},"vaultAddress":{"type":"string","nullable":true}}},"BuilderOrder":{"type":"object","required":["symbolCode","ordPx","ordQty","ordType","ordSide","timeInForce"],"properties":{"symbolCode":{"type":"integer","format":"int64"},"ordPx":{"type":"string","description":"Limit price; use `0` for a market order"},"ordQty":{"type":"string"},"ordType":{"type":"string","enum":["LIMIT","MARKET","STOP_LIMIT","STOP_MARKET","TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"]},"ordSide":{"type":"string","enum":["BUY","SELL","BUY_CLOSE_HEDGE","SELL_CLOSE_HEDGE"]},"timeInForce":{"type":"string","enum":["GTC","IOC","FOK","POST_ONLY"]},"clOrdId":{"type":"integer","format":"int64"},"parentOrdId":{"type":"integer","format":"int64"},"reduceOnly":{"type":"string","enum":["REDUCE_ONLY","TP_FROM_POSITION","SL_FROM_POSITION"],"description":"`reduceOnlyOption` is accepted as a compatibility alias."},"triggerPx":{"type":"string"},"tpslTriggerType":{"type":"string","enum":["LAST_PRICE","MARK_PRICE","INDEX_PRICE"]},"slippagePct":{"type":"string"}}},"Signature":{"type":"object","required":["r","s","v"],"properties":{"r":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"s":{"type":"string","description":"32-byte hex, zero-padded to 64 chars"},"v":{"type":"integer","description":"27 or 28"}}}}}}
```


# Info API

Query account, orders, positions, trades, kline, funding rate, and more.

Query endpoints for all read-only data. No signature required.

```
GET /info/...
```

## Python SDK Examples

The official SDK repository includes runnable examples for read-only queries:

* Market data: [get\_products.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_products.py), [get\_kline.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_kline.py), [get\_funding\_rate\_current.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_funding_rate_current.py)
* Account data: [get\_wallet.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_wallet.py), [get\_orders.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_orders.py), [get\_positions.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_positions.py)
* Agent data: [get\_agents.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_agents.py), [get\_active\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_active_agent.py)


# Account

## GET /info/account/wallet

> Query Wallet Balances

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/account/wallet":{"get":{"operationId":"queryWallet","summary":"Query Wallet Balances","tags":["Account"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"},"description":"User address (0x hex)"},{"name":"currency","in":"query","schema":{"type":"integer","format":"int64"},"description":"Currency code filter"},{"name":"includeZero","in":"query","schema":{"type":"boolean","default":false},"description":"Include zero-balance currencies"}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"message":{"type":"string"},"data":{"type":"array","items":{"$ref":"#/components/schemas/AccountWallet"}}}}}}}}}}},"components":{"schemas":{"AccountWallet":{"type":"object","properties":{"blockHeight":{"type":"integer","format":"int64"},"userAddr":{"type":"string"},"currency":{"type":"integer","format":"int64"},"balance":{"type":"string"},"availableBalance":{"type":"string"},"availableTransferBalance":{"type":"string"},"equity":{"type":"string"},"status":{"type":"string"},"blockTime":{"type":"integer","format":"int64"}}}}}}
```

## GET /info/account/ledger

> Query Account Ledger

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/account/ledger":{"get":{"operationId":"queryLedger","summary":"Query Account Ledger","tags":["Account"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"currency","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"bizType","in":"query","schema":{"type":"string"},"description":"Business type filter"},{"name":"txHash","in":"query","schema":{"type":"string"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"},"description":"Start timestamp (ms)"},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"},"description":"End timestamp (ms)"}],"responses":{"200":{"description":"Paginated ledger entries"}}}}}}
```

## GET /info/account/agent

> Query Account Agents

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/account/agent":{"get":{"operationId":"queryAgent","summary":"Query Account Agents","tags":["Account"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"role","in":"query","schema":{"type":"string"}},{"name":"status","in":"query","schema":{"type":"string"}},{"name":"agentAddress","in":"query","schema":{"type":"string"}},{"name":"masterAddress","in":"query","schema":{"type":"string"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Paginated agent list","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/AccountAgent"}}}}}}}}}}},"components":{"schemas":{"AccountAgent":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"masterAddress":{"type":"string"},"agentAddress":{"type":"string"},"agentName":{"type":"string"},"status":{"type":"string","description":"1=ACTIVE, 2=REVOKED"},"permission":{"type":"string"},"approvedAt":{"type":"integer","format":"int64"},"approvedBlock":{"type":"integer","format":"int64"},"approvalTx":{"type":"string"},"revokedAt":{"type":"integer","format":"int64"},"revokedBlock":{"type":"integer","format":"int64"},"revokeTx":{"type":"string"}}}}}}
```

## GET /info/account/agent/active

> Query Active Agent

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/account/agent/active":{"get":{"operationId":"queryActiveAgent","summary":"Query Active Agent","tags":["Account"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"agentName","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Active agent info","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"$ref":"#/components/schemas/AccountAgent"}}}}}}}}}},"components":{"schemas":{"AccountAgent":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"masterAddress":{"type":"string"},"agentAddress":{"type":"string"},"agentName":{"type":"string"},"status":{"type":"string","description":"1=ACTIVE, 2=REVOKED"},"permission":{"type":"string"},"approvedAt":{"type":"integer","format":"int64"},"approvedBlock":{"type":"integer","format":"int64"},"approvalTx":{"type":"string"},"revokedAt":{"type":"integer","format":"int64"},"revokedBlock":{"type":"integer","format":"int64"},"revokeTx":{"type":"string"}}}}}}
```


# Orders

## GET /info/order/states

> Query Order States

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/order/states":{"get":{"operationId":"queryOrderStates","summary":"Query Order States","tags":["Orders"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"symbol","in":"query","schema":{"type":"integer","format":"int64"},"description":"Symbol code filter"},{"name":"status","in":"query","schema":{"type":"string"},"description":"Order status filter"},{"name":"side","in":"query","schema":{"type":"integer"},"description":"Side filter (1=BUY, 2=SELL)"},{"name":"type","in":"query","schema":{"type":"integer"},"description":"Type filter (1=LIMIT, 2=MARKET)"},{"name":"orderId","in":"query","schema":{"type":"string"}},{"name":"clientOrderId","in":"query","schema":{"type":"string"}},{"name":"parentOrderId","in":"query","schema":{"type":"string"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Paginated order states","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/OrderState"}}}}}}}}}}},"components":{"schemas":{"OrderState":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"blockHeight":{"type":"integer","format":"int64"},"ordId":{"type":"string"},"clOrdId":{"type":"string"},"parentOrdId":{"type":"string"},"userAddr":{"type":"string"},"symbol":{"type":"integer","format":"int64"},"side":{"type":"integer","description":"1=BUY, 2=SELL"},"type":{"type":"integer","description":"1=LIMIT, 2=MARKET"},"price":{"type":"string"},"qty":{"type":"string"},"filledQty":{"type":"string"},"leaveQty":{"type":"string"},"cumFilledValue":{"type":"string"},"cumFee":{"type":"string"},"triggerPx":{"type":"string"},"status":{"type":"string","description":"NEW, PARTIALLY_FILLED, FILLED, CANCELED"},"timeInForce":{"type":"string"},"reduceOnly":{"type":"integer","description":"0=NONE, 1=REDUCE_ONLY, 2=TP, 3=SL"},"conditionalOrderTriggerType":{"type":"integer"},"blockTime":{"type":"integer","format":"int64"}}}}}}
```

## GET /info/order/events

> Query Order Events

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/order/events":{"get":{"operationId":"queryOrderEvents","summary":"Query Order Events","tags":["Orders"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"orderId","in":"query","schema":{"type":"string"}},{"name":"clientOrderId","in":"query","schema":{"type":"string"}},{"name":"symbol","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"execStatus","in":"query","schema":{"type":"string"}},{"name":"side","in":"query","schema":{"type":"integer"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Paginated order events","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/OrderEvent"}}}}}}}}}}},"components":{"schemas":{"OrderEvent":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"blockHeight":{"type":"integer","format":"int64"},"userAddr":{"type":"string"},"ordId":{"type":"string"},"clOrdId":{"type":"string"},"symbol":{"type":"integer","format":"int64"},"side":{"type":"string"},"execStatus":{"type":"string"},"ordPx":{"type":"string"},"filledPx":{"type":"string"},"execQty":{"type":"string"},"leavesQty":{"type":"string"},"execId":{"type":"string"},"realizedPnl":{"type":"string"},"openFee":{"type":"string"},"closeFee":{"type":"string"},"blockTime":{"type":"integer","format":"int64"},"txHash":{"type":"string"},"ordType":{"type":"integer"},"timeInForce":{"type":"string"},"ordQty":{"type":"string"},"triggerPx":{"type":"string"}}}}}}
```


# Positions

## GET /info/position/list

> Query Positions

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/position/list":{"get":{"operationId":"queryPositions","summary":"Query Positions","tags":["Positions"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"symbol","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"posMode","in":"query","schema":{"type":"integer"},"description":"Position mode (1=ONE_WAY, 2=HEDGE)"},{"name":"includeZero","in":"query","schema":{"type":"boolean","default":false}}],"responses":{"200":{"description":"Position list","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Position"}}}}}}}}}}},"components":{"schemas":{"Position":{"type":"object","properties":{"userAddr":{"type":"string"},"symbolCode":{"type":"integer","format":"int64"},"leverage":{"type":"string"},"longSize":{"type":"string"},"shortSize":{"type":"string"},"longEntryValue":{"type":"string"},"shortEntryValue":{"type":"string"},"positionMode":{"type":"string","description":"ONE_WAY, HEDGE"},"positionMarginMode":{"type":"string","description":"CROSS, ISOLATED"},"assignedPosBalance":{"type":"string"},"unrealizedPnl":{"type":"string"},"cumRealizedPnl":{"type":"string"},"curMarkPx":{"type":"string"},"cumTransactionFee":{"type":"string"},"createTime":{"type":"integer","format":"int64"},"blockTime":{"type":"integer","format":"int64"}}}}}}
```


# Trades

## GET /info/trade/page

> Query Trades

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/trade/page":{"get":{"operationId":"queryTrades","summary":"Query Trades","tags":["Trades"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"symbol","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"orderId","in":"query","schema":{"type":"string"}},{"name":"execId","in":"query","schema":{"type":"string"}},{"name":"side","in":"query","schema":{"type":"integer"}},{"name":"role","in":"query","schema":{"type":"string"},"description":"Maker/Taker role filter"},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Paginated trade records","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Trade"}}}}}}}}}}},"components":{"schemas":{"Trade":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"blockHeight":{"type":"integer","format":"int64"},"userAddr":{"type":"string"},"symbol":{"type":"integer","format":"int64"},"orderId":{"type":"string"},"clientOrderId":{"type":"string"},"side":{"type":"string"},"execStatus":{"type":"string"},"orderPx":{"type":"string"},"filledPx":{"type":"string"},"execQty":{"type":"string"},"leavesQty":{"type":"string"},"execId":{"type":"string"},"realizedPnl":{"type":"string"},"openFee":{"type":"string"},"closeFee":{"type":"string"},"blockTime":{"type":"integer","format":"int64"},"txHash":{"type":"string"}}}}}}
```


# Products

## GET /info/single

> Query Single Product

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/single":{"get":{"operationId":"getProductSingle","summary":"Query Single Product","tags":["Products"],"parameters":[{"name":"symbol","in":"query","required":true,"schema":{"type":"integer","format":"int64"},"description":"Symbol code"}],"responses":{"200":{"description":"Product metadata","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"$ref":"#/components/schemas/ProductMeta"}}}}}}}}}},"components":{"schemas":{"ProductMeta":{"type":"object","properties":{"md5Checksum":{"type":"string"},"perpProducts":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Display name"},"symbol":{"type":"string","description":"Symbol name e.g. BTCUSDC"},"code":{"type":"string","description":"Symbol code"},"currencyCode":{"type":"integer","format":"int64"},"maxLeverage":{"type":"integer"},"pricePrecision":{"type":"integer"},"qtyPrecision":{"type":"integer"},"tickSize":{"type":"string"},"stepSize":{"type":"string"},"maxOrderQty":{"type":"integer","format":"int64"},"maxSlippagePct":{"type":"string"},"maxPositionNtnl":{"type":"integer","format":"int64"},"fundingInterval":{"type":"integer","format":"int64","description":"seconds"},"productType":{"type":"string"},"listStatus":{"type":"string"},"onlyIsolated":{"type":"boolean"},"baseCurrency":{"type":"string"},"quoteCurrency":{"type":"string"},"settleCurrency":{"type":"string"},"minOrderValue":{"type":"string"},"defaultMakerFeeRate":{"type":"string"},"defaultTakerFeeRate":{"type":"string"}}}},"marginTables":{"type":"array","items":{"type":"object","properties":{"tableId":{"type":"integer"},"riskLimitVo":{"type":"array","items":{"type":"object","properties":{"minimumValue":{"type":"string"},"maintainMarginRatio":{"type":"string"},"maxLeverage":{"type":"integer"}}}}}}},"currencies":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"currency":{"type":"string"},"code":{"type":"integer","format":"int64"},"walletPrecision":{"type":"integer"},"displayPrecision":{"type":"integer"}}}}}}}}}
```

## GET /info/public/product-meta

> Query All Products

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/public/product-meta":{"get":{"operationId":"getAllProducts","summary":"Query All Products","tags":["Products"],"parameters":[{"name":"listStatus","in":"query","schema":{"type":"integer"},"description":"Filter by listing status"}],"responses":{"200":{"description":"All product metadata","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"$ref":"#/components/schemas/ProductMeta"}}}}}}}}}},"components":{"schemas":{"ProductMeta":{"type":"object","properties":{"md5Checksum":{"type":"string"},"perpProducts":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Display name"},"symbol":{"type":"string","description":"Symbol name e.g. BTCUSDC"},"code":{"type":"string","description":"Symbol code"},"currencyCode":{"type":"integer","format":"int64"},"maxLeverage":{"type":"integer"},"pricePrecision":{"type":"integer"},"qtyPrecision":{"type":"integer"},"tickSize":{"type":"string"},"stepSize":{"type":"string"},"maxOrderQty":{"type":"integer","format":"int64"},"maxSlippagePct":{"type":"string"},"maxPositionNtnl":{"type":"integer","format":"int64"},"fundingInterval":{"type":"integer","format":"int64","description":"seconds"},"productType":{"type":"string"},"listStatus":{"type":"string"},"onlyIsolated":{"type":"boolean"},"baseCurrency":{"type":"string"},"quoteCurrency":{"type":"string"},"settleCurrency":{"type":"string"},"minOrderValue":{"type":"string"},"defaultMakerFeeRate":{"type":"string"},"defaultTakerFeeRate":{"type":"string"}}}},"marginTables":{"type":"array","items":{"type":"object","properties":{"tableId":{"type":"integer"},"riskLimitVo":{"type":"array","items":{"type":"object","properties":{"minimumValue":{"type":"string"},"maintainMarginRatio":{"type":"string"},"maxLeverage":{"type":"integer"}}}}}}},"currencies":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"currency":{"type":"string"},"code":{"type":"integer","format":"int64"},"walletPrecision":{"type":"integer"},"displayPrecision":{"type":"integer"}}}}}}}}}
```


# Kline

## Query Latest Klines

> Get latest N kline candles, sorted by timestamp descending.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/kline/last":{"get":{"operationId":"getKlineLast","summary":"Query Latest Klines","tags":["Kline"],"description":"Get latest N kline candles, sorted by timestamp descending.","parameters":[{"name":"symbol_name","in":"query","required":true,"schema":{"type":"string"},"description":"Symbol name (e.g. `BTCUSDC`)"},{"name":"interval","in":"query","required":true,"schema":{"type":"integer","format":"int64"},"description":"Interval in seconds (60, 300, 900, 3600, 86400, ...)"},{"name":"limit","in":"query","schema":{"type":"integer","default":100},"description":"Number of candles to return"}],"responses":{"200":{"description":"Kline data array","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Kline"}}}}}}}}}}},"components":{"schemas":{"Kline":{"type":"object","properties":{"symbolName":{"type":"string"},"timestamp":{"type":"integer","format":"int64","description":"K-line start time (seconds)"},"intrvl":{"type":"integer","format":"int64","description":"Interval (seconds)"},"open":{"type":"string"},"high":{"type":"string"},"low":{"type":"string"},"close":{"type":"string"},"volume":{"type":"string"},"turnover":{"type":"string"},"tradeCount":{"type":"integer","format":"int64"}}}}}}
```

## Query Klines Before Timestamp

> Get N klines before a given timestamp. Defaults to current time.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/kline/before":{"get":{"operationId":"getKlineBefore","summary":"Query Klines Before Timestamp","tags":["Kline"],"description":"Get N klines before a given timestamp. Defaults to current time.","parameters":[{"name":"symbol_name","in":"query","required":true,"schema":{"type":"string"}},{"name":"interval","in":"query","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"timestamp","in":"query","schema":{"type":"integer","format":"int64"},"description":"Upper bound timestamp (ms). Defaults to now."},{"name":"limit","in":"query","schema":{"type":"integer","default":100}}],"responses":{"200":{"description":"Kline data array","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Kline"}}}}}}}}}}},"components":{"schemas":{"Kline":{"type":"object","properties":{"symbolName":{"type":"string"},"timestamp":{"type":"integer","format":"int64","description":"K-line start time (seconds)"},"intrvl":{"type":"integer","format":"int64","description":"Interval (seconds)"},"open":{"type":"string"},"high":{"type":"string"},"low":{"type":"string"},"close":{"type":"string"},"volume":{"type":"string"},"turnover":{"type":"string"},"tradeCount":{"type":"integer","format":"int64"}}}}}}
```

## Query Klines in Time Range

> Get all klines in a time range, sorted ascending.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/kline/list":{"get":{"operationId":"getKlineList","summary":"Query Klines in Time Range","tags":["Kline"],"description":"Get all klines in a time range, sorted ascending.","parameters":[{"name":"symbol_name","in":"query","required":true,"schema":{"type":"string"}},{"name":"interval","in":"query","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"startTime","in":"query","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","required":true,"schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Kline data array","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Kline"}}}}}}}}}}},"components":{"schemas":{"Kline":{"type":"object","properties":{"symbolName":{"type":"string"},"timestamp":{"type":"integer","format":"int64","description":"K-line start time (seconds)"},"intrvl":{"type":"integer","format":"int64","description":"Interval (seconds)"},"open":{"type":"string"},"high":{"type":"string"},"low":{"type":"string"},"close":{"type":"string"},"volume":{"type":"string"},"turnover":{"type":"string"},"tradeCount":{"type":"integer","format":"int64"}}}}}}
```


# Funding Rate

## GET /info/fundingRate/current

> Query Current Funding Rates

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/fundingRate/current":{"get":{"operationId":"getFundingRateCurrent","summary":"Query Current Funding Rates","tags":["Funding Rate"],"parameters":[{"name":"symbol","in":"query","schema":{"type":"integer","format":"int64"},"description":"Symbol code. Omit for all symbols."}],"responses":{"200":{"description":"Current funding rate(s)"}}}}}}
```

## GET /info/fundingRate/history

> Query Funding Rate History

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/fundingRate/history":{"get":{"operationId":"getFundingRateHistory","summary":"Query Funding Rate History","tags":["Funding Rate"],"parameters":[{"name":"symbol","in":"query","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Paginated funding rate history"}}}}}}
```

## Query User Funding History

> Query a user's funding fee settlement history.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/funding/history":{"get":{"operationId":"queryUserFundingHistory","summary":"Query User Funding History","tags":["Funding Rate"],"description":"Query a user's funding fee settlement history.","parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"symbol","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Paginated user funding history"}}}}}}
```


# Vault

## Query Vault Detail

> Returns vault info (TVL, APR, PnL). If \`userAddress\` is provided, also returns user position data.\
> When querying a parent vault, TVL/PnL/APR aggregate all sub-vaults.<br>

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/detail":{"get":{"operationId":"getVaultDetail","summary":"Query Vault Detail","tags":["Vault"],"description":"Returns vault info (TVL, APR, PnL). If `userAddress` is provided, also returns user position data.\nWhen querying a parent vault, TVL/PnL/APR aggregate all sub-vaults.\n","parameters":[{"name":"vaultAddress","in":"query","required":true,"schema":{"type":"string"}},{"name":"userAddress","in":"query","schema":{"type":"string"},"description":"Include user position data"}],"responses":{"200":{"description":"Vault detail","content":{"application/json":{}}}}}}}}
```

## Query User's Vault List

> Returns all vaults where user holds shares > 0.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/user-list":{"get":{"operationId":"getUserVaultList","summary":"Query User's Vault List","tags":["Vault"],"description":"Returns all vaults where user holds shares > 0.","parameters":[{"name":"userAddress","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"List of vaults with user holdings"}}}}}}
```

## Query User Vault Position

> Returns user's full position info in a specific vault.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/user":{"get":{"operationId":"getUserVaultInfo","summary":"Query User Vault Position","tags":["Vault"],"description":"Returns user's full position info in a specific vault.","parameters":[{"name":"vaultAddress","in":"query","required":true,"schema":{"type":"string"}},{"name":"userAddress","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"User vault position detail"}}}}}}
```

## Query All Vaults

> Returns all parent vaults (Active and Closed). Sub-vaults not listed.\
> TVL and APR aggregate sub-vault data.<br>

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/list":{"get":{"operationId":"getVaultList","summary":"Query All Vaults","tags":["Vault"],"description":"Returns all parent vaults (Active and Closed). Sub-vaults not listed.\nTVL and APR aggregate sub-vault data.\n","parameters":[{"name":"userAddress","in":"query","schema":{"type":"string"},"description":"Include `yourDeposit` field when provided"}],"responses":{"200":{"description":"Vault list with total locked value"}}}}}}
```

## Query Vault History

> Returns vault TVL or PnL time-series data.\
> \
> \| interval | Range | Granularity |\
> \|----------|-------|-------------|\
> \| 24h | Last 24 hours | 1 hour |\
> \| 7d | Last 7 days | 12 hours |\
> \| 30d | Last 30 days | 1 day |\
> \| all-time | All history | 1 month |<br>

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/history":{"get":{"operationId":"getVaultHistory","summary":"Query Vault History","tags":["Vault"],"description":"Returns vault TVL or PnL time-series data.\n\n| interval | Range | Granularity |\n|----------|-------|-------------|\n| 24h | Last 24 hours | 1 hour |\n| 7d | Last 7 days | 12 hours |\n| 30d | Last 30 days | 1 day |\n| all-time | All history | 1 month |\n","parameters":[{"name":"vaultAddress","in":"query","required":true,"schema":{"type":"string"}},{"name":"type","in":"query","schema":{"type":"string","default":"tvl","enum":["tvl","pnl"]}},{"name":"interval","in":"query","schema":{"type":"string","default":"24h","enum":["24h","7d","30d","all-time"]}}],"responses":{"200":{"description":"Time-series data"}}}}}}
```

## GET /info/vault/events

> Query Vault Deposit/Withdraw Events

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/events":{"get":{"operationId":"getVaultEvents","summary":"Query Vault Deposit/Withdraw Events","tags":["Vault"],"parameters":[{"name":"vaultAddress","in":"query","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Paginated deposit/withdraw events"}}}}}}
```

## Query Vault Depositors

> Returns all depositors with shares > 0.

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/vault/depositors":{"get":{"operationId":"getVaultDepositors","summary":"Query Vault Depositors","tags":["Vault"],"description":"Returns all depositors with shares > 0.","parameters":[{"name":"vaultAddress","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Depositor list"}}}}}}
```


# Referral

## GET /info/referral/code

> Query Referral Code

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/referral/code":{"get":{"operationId":"getReferralCode","summary":"Query Referral Code","tags":["Referral"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Referral code info"}}}}}}
```

## GET /info/referral/summary

> Query Referral Summary

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/referral/summary":{"get":{"operationId":"getReferralSummary","summary":"Query Referral Summary","tags":["Referral"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"period","in":"query","schema":{"type":"string","default":"all"}},{"name":"startTime","in":"query","schema":{"type":"integer","format":"int64"}},{"name":"endTime","in":"query","schema":{"type":"integer","format":"int64"}}],"responses":{"200":{"description":"Referral summary statistics"}}}}}}
```

## GET /info/referral/referrals

> Query Referral List

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/referral/referrals":{"get":{"operationId":"getReferrals","summary":"Query Referral List","tags":["Referral"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"size","in":"query","schema":{"type":"integer","default":10}},{"name":"sortBy","in":"query","schema":{"type":"string","default":"dateJoined"}},{"name":"sortOrder","in":"query","schema":{"type":"string","default":"desc"}},{"name":"search","in":"query","schema":{"type":"string"}}],"responses":{"200":{"description":"Paginated referral list"}}}}}}
```

## GET /info/referral/payouts

> Query Referral Payouts

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/referral/payouts":{"get":{"operationId":"getPayouts","summary":"Query Referral Payouts","tags":["Referral"],"parameters":[{"name":"userAddr","in":"query","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"size","in":"query","schema":{"type":"integer","default":10}}],"responses":{"200":{"description":"Paginated payout list"}}}}}}
```

## Query Referral Tiers

> Returns referral tier configuration (no parameters).

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/referral/tiers":{"get":{"operationId":"getTierConfigs","summary":"Query Referral Tiers","tags":["Referral"],"description":"Returns referral tier configuration (no parameters).","responses":{"200":{"description":"Tier config list"}}}}}}
```


# Explorer

## GET /info/explore/transaction/page

> Query Transactions

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/explore/transaction/page":{"get":{"operationId":"queryTransactions","summary":"Query Transactions","tags":["Explorer"],"parameters":[{"name":"user","in":"query","required":true,"schema":{"type":"string"},"description":"User address"},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Paginated transaction list"}}}}}}
```

## GET /info/explore/transaction/detail

> Query Transaction Detail

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/explore/transaction/detail":{"get":{"operationId":"queryTransactionDetail","summary":"Query Transaction Detail","tags":["Explorer"],"parameters":[{"name":"txHash","in":"query","schema":{"type":"string"}}],"responses":{"200":{"description":"Transaction detail with parsed action"}}}}}}
```

## GET /info/explore/block/detail

> Query Block Detail

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"servers":[{"url":"https://api.afx.xyz","description":"Mainnet"},{"url":"https://api-testnet.afx.xyz","description":"Testnet"}],"paths":{"/info/explore/block/detail":{"get":{"operationId":"queryBlockDetail","summary":"Query Block Detail","tags":["Explorer"],"parameters":[{"name":"blockHeight","in":"query","required":true,"schema":{"type":"integer","format":"int64"}},{"name":"page","in":"query","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Block detail with paginated transactions"}}}}}}
```


# Models

## The AccountWallet object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"AccountWallet":{"type":"object","properties":{"blockHeight":{"type":"integer","format":"int64"},"userAddr":{"type":"string"},"currency":{"type":"integer","format":"int64"},"balance":{"type":"string"},"availableBalance":{"type":"string"},"availableTransferBalance":{"type":"string"},"equity":{"type":"string"},"status":{"type":"string"},"blockTime":{"type":"integer","format":"int64"}}}}}}
```

## The AccountAgent object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"AccountAgent":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"masterAddress":{"type":"string"},"agentAddress":{"type":"string"},"agentName":{"type":"string"},"status":{"type":"string","description":"1=ACTIVE, 2=REVOKED"},"permission":{"type":"string"},"approvedAt":{"type":"integer","format":"int64"},"approvedBlock":{"type":"integer","format":"int64"},"approvalTx":{"type":"string"},"revokedAt":{"type":"integer","format":"int64"},"revokedBlock":{"type":"integer","format":"int64"},"revokeTx":{"type":"string"}}}}}}
```

## The OrderState object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"OrderState":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"blockHeight":{"type":"integer","format":"int64"},"ordId":{"type":"string"},"clOrdId":{"type":"string"},"parentOrdId":{"type":"string"},"userAddr":{"type":"string"},"symbol":{"type":"integer","format":"int64"},"side":{"type":"integer","description":"1=BUY, 2=SELL"},"type":{"type":"integer","description":"1=LIMIT, 2=MARKET"},"price":{"type":"string"},"qty":{"type":"string"},"filledQty":{"type":"string"},"leaveQty":{"type":"string"},"cumFilledValue":{"type":"string"},"cumFee":{"type":"string"},"triggerPx":{"type":"string"},"status":{"type":"string","description":"NEW, PARTIALLY_FILLED, FILLED, CANCELED"},"timeInForce":{"type":"string"},"reduceOnly":{"type":"integer","description":"0=NONE, 1=REDUCE_ONLY, 2=TP, 3=SL"},"conditionalOrderTriggerType":{"type":"integer"},"blockTime":{"type":"integer","format":"int64"}}}}}}
```

## The OrderEvent object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"OrderEvent":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"blockHeight":{"type":"integer","format":"int64"},"userAddr":{"type":"string"},"ordId":{"type":"string"},"clOrdId":{"type":"string"},"symbol":{"type":"integer","format":"int64"},"side":{"type":"string"},"execStatus":{"type":"string"},"ordPx":{"type":"string"},"filledPx":{"type":"string"},"execQty":{"type":"string"},"leavesQty":{"type":"string"},"execId":{"type":"string"},"realizedPnl":{"type":"string"},"openFee":{"type":"string"},"closeFee":{"type":"string"},"blockTime":{"type":"integer","format":"int64"},"txHash":{"type":"string"},"ordType":{"type":"integer"},"timeInForce":{"type":"string"},"ordQty":{"type":"string"},"triggerPx":{"type":"string"}}}}}}
```

## The Position object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"Position":{"type":"object","properties":{"userAddr":{"type":"string"},"symbolCode":{"type":"integer","format":"int64"},"leverage":{"type":"string"},"longSize":{"type":"string"},"shortSize":{"type":"string"},"longEntryValue":{"type":"string"},"shortEntryValue":{"type":"string"},"positionMode":{"type":"string","description":"ONE_WAY, HEDGE"},"positionMarginMode":{"type":"string","description":"CROSS, ISOLATED"},"assignedPosBalance":{"type":"string"},"unrealizedPnl":{"type":"string"},"cumRealizedPnl":{"type":"string"},"curMarkPx":{"type":"string"},"cumTransactionFee":{"type":"string"},"createTime":{"type":"integer","format":"int64"},"blockTime":{"type":"integer","format":"int64"}}}}}}
```

## The Trade object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"Trade":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"blockHeight":{"type":"integer","format":"int64"},"userAddr":{"type":"string"},"symbol":{"type":"integer","format":"int64"},"orderId":{"type":"string"},"clientOrderId":{"type":"string"},"side":{"type":"string"},"execStatus":{"type":"string"},"orderPx":{"type":"string"},"filledPx":{"type":"string"},"execQty":{"type":"string"},"leavesQty":{"type":"string"},"execId":{"type":"string"},"realizedPnl":{"type":"string"},"openFee":{"type":"string"},"closeFee":{"type":"string"},"blockTime":{"type":"integer","format":"int64"},"txHash":{"type":"string"}}}}}}
```

## The ProductMeta object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"ProductMeta":{"type":"object","properties":{"md5Checksum":{"type":"string"},"perpProducts":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Display name"},"symbol":{"type":"string","description":"Symbol name e.g. BTCUSDC"},"code":{"type":"string","description":"Symbol code"},"currencyCode":{"type":"integer","format":"int64"},"maxLeverage":{"type":"integer"},"pricePrecision":{"type":"integer"},"qtyPrecision":{"type":"integer"},"tickSize":{"type":"string"},"stepSize":{"type":"string"},"maxOrderQty":{"type":"integer","format":"int64"},"maxSlippagePct":{"type":"string"},"maxPositionNtnl":{"type":"integer","format":"int64"},"fundingInterval":{"type":"integer","format":"int64","description":"seconds"},"productType":{"type":"string"},"listStatus":{"type":"string"},"onlyIsolated":{"type":"boolean"},"baseCurrency":{"type":"string"},"quoteCurrency":{"type":"string"},"settleCurrency":{"type":"string"},"minOrderValue":{"type":"string"},"defaultMakerFeeRate":{"type":"string"},"defaultTakerFeeRate":{"type":"string"}}}},"marginTables":{"type":"array","items":{"type":"object","properties":{"tableId":{"type":"integer"},"riskLimitVo":{"type":"array","items":{"type":"object","properties":{"minimumValue":{"type":"string"},"maintainMarginRatio":{"type":"string"},"maxLeverage":{"type":"integer"}}}}}}},"currencies":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"currency":{"type":"string"},"code":{"type":"integer","format":"int64"},"walletPrecision":{"type":"integer"},"displayPrecision":{"type":"integer"}}}}}}}}}
```

## The Kline object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX Info API","version":"1.0.0"},"components":{"schemas":{"Kline":{"type":"object","properties":{"symbolName":{"type":"string"},"timestamp":{"type":"integer","format":"int64","description":"K-line start time (seconds)"},"intrvl":{"type":"integer","format":"int64","description":"Interval (seconds)"},"open":{"type":"string"},"high":{"type":"string"},"low":{"type":"string"},"close":{"type":"string"},"volume":{"type":"string"},"turnover":{"type":"string"},"tradeCount":{"type":"integer","format":"int64"}}}}}}
```


# WebSocket

Real-time market data and account updates via WebSocket.

Persistent connection for real-time orderbook, kline, ticker, trades, and account state updates.

WebSocket operations are JSON messages sent over an open WebSocket connection. They are not HTTP `POST` requests.

| Environment | URL                               |
| ----------- | --------------------------------- |
| Mainnet     | `wss://ws.afx.xyz/ws/dex`         |
| Testnet     | `wss://ws-testnet.afx.xyz/ws/dex` |

## Python SDK Examples

The official SDK repository includes runnable WebSocket examples:

* [subscribe.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe.py)
* [subscribe\_order\_book.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_order_book.py)
* [subscribe\_ticker.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_ticker.py)
* [subscribe\_account\_state.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_account_state.py)


# Connection

## Ping / Pong

> Send a heartbeat to keep the connection alive.\
> \
> \`\`\`json\
> { "method": "ping" }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/ping":{"post":{"operationId":"wsPing","summary":"Ping / Pong","tags":["Connection"],"description":"Send a heartbeat to keep the connection alive.\n\n```json\n{ \"method\": \"ping\" }\n```\n","responses":{"200":{"description":"Pong","content":{"application/json":{}}}}}}}}
````

## Unsubscribe

> Unsubscribe from a channel. Send the same \`subscription\` object used to subscribe.\
> \
> \`\`\`json\
> { "method": "unsubscribe", "subscription": { "type": "orderBook", "symbol": "BTCUSDC", "depth": 50 } }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/unsubscribe":{"post":{"operationId":"wsUnsubscribe","summary":"Unsubscribe","tags":["Connection"],"description":"Unsubscribe from a channel. Send the same `subscription` object used to subscribe.\n\n```json\n{ \"method\": \"unsubscribe\", \"subscription\": { \"type\": \"orderBook\", \"symbol\": \"BTCUSDC\", \"depth\": 50 } }\n```\n","responses":{"200":{"description":"Ack","content":{"application/json":{}}}}}}}}
````


# Market Data

## Order Book

> Subscribe to order book depth updates. Sends initial snapshot then incremental deltas.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "orderBook", "symbol": "BTCUSDC", "depth": 50 } }\
> \`\`\`\
> \
> \| Param | Type | Required | Description |\
> \|-------|------|----------|-------------|\
> \| symbol | string | Yes | Symbol name |\
> \| depth | integer | No | Depth level (default 5) |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/orderBook":{"post":{"operationId":"wsOrderBook","summary":"Order Book","tags":["Market Data"],"description":"Subscribe to order book depth updates. Sends initial snapshot then incremental deltas.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"orderBook\", \"symbol\": \"BTCUSDC\", \"depth\": 50 } }\n```\n\n| Param | Type | Required | Description |\n|-------|------|----------|-------------|\n| symbol | string | Yes | Symbol name |\n| depth | integer | No | Depth level (default 5) |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderBookPush"}}}}}}}},"components":{"schemas":{"OrderBookPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"symbolCode":{"type":"integer","description":"Symbol code"},"symbol":{"type":"string","description":"Symbol name"},"block":{"type":"integer","description":"Block height"},"sequence":{"type":"integer","description":"Sequence number"},"depth":{"type":"integer","description":"Requested depth"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"book":{"type":"object","properties":{"bids":{"type":"array","description":"Bid levels `[price, qty]`","items":{"type":"array","items":{"type":"string"}}},"asks":{"type":"array","description":"Ask levels `[price, qty]`","items":{"type":"array","items":{"type":"string"}}}}}}}}}}}}
````

## Kline / Candle

> Subscribe to candlestick (OHLCV) data.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "candle", "symbol": "BTCUSDC", "interval": "60" } }\
> \`\`\`\
> \
> \| Param | Type | Required | Description |\
> \|-------|------|----------|-------------|\
> \| symbol | string | Yes | Symbol name |\
> \| interval | string | Yes | Interval in seconds ("60", "300", "900", "3600", "86400") |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/candle":{"post":{"operationId":"wsCandle","summary":"Kline / Candle","tags":["Market Data"],"description":"Subscribe to candlestick (OHLCV) data.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"candle\", \"symbol\": \"BTCUSDC\", \"interval\": \"60\" } }\n```\n\n| Param | Type | Required | Description |\n|-------|------|----------|-------------|\n| symbol | string | Yes | Symbol name |\n| interval | string | Yes | Interval in seconds (\"60\", \"300\", \"900\", \"3600\", \"86400\") |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CandlePush"}}}}}}}},"components":{"schemas":{"CandlePush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"symbolName":{"type":"string","description":"Symbol name"},"timestamp":{"type":"integer","description":"Candle start time (seconds)"},"intrvl":{"type":"integer","description":"Interval (seconds)"},"open":{"type":"string","description":"Open price"},"high":{"type":"string","description":"High price"},"low":{"type":"string","description":"Low price"},"close":{"type":"string","description":"Close price"},"volume":{"type":"string","description":"Trading volume"},"turnover":{"type":"string","description":"Trading turnover (value)"},"tradeCount":{"type":"integer","description":"Number of trades"}}}}}}}}
````

## Recent Trades

> Subscribe to recent trade updates.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "trades", "symbol": "BTCUSDC" } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| symbol | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/trades":{"post":{"operationId":"wsTrades","summary":"Recent Trades","tags":["Market Data"],"description":"Subscribe to recent trade updates.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"trades\", \"symbol\": \"BTCUSDC\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| symbol | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TradesPush"}}}}}}}},"components":{"schemas":{"TradesPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"sequence":{"type":"integer","description":"Sequence number"},"symbol":{"type":"string","description":"Symbol name"},"trades":{"type":"array","items":{"type":"object","properties":{"symbol":{"type":"string"},"ordSide":{"type":"string","description":"BUY or SELL"},"filledPx":{"type":"string","description":"Trade price"},"filledQty":{"type":"string","description":"Trade quantity"},"transactionTime":{"type":"integer","description":"Timestamp (ms)"},"txHash":{"type":"string","description":"On-chain tx hash"}}}}}}}}}}}
````

## Ticker

> Subscribe to single symbol ticker.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "ticker", "symbol": "BTCUSDC" } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| symbol | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/ticker":{"post":{"operationId":"wsTicker","summary":"Ticker","tags":["Market Data"],"description":"Subscribe to single symbol ticker.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"ticker\", \"symbol\": \"BTCUSDC\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| symbol | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TickerPush"}}}}}}}},"components":{"schemas":{"TickerPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"sequence":{"type":"integer","description":"Sequence number"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"symbol":{"type":"string","description":"Symbol name"},"ticker":{"type":"object","properties":{"s":{"type":"string","description":"Symbol"},"p":{"type":"string","description":"Last price"},"op":{"type":"string","description":"Oracle price"},"mp":{"type":"string","description":"Mark price"},"mid":{"type":"string","description":"Mid price"},"oi":{"type":"string","description":"Open interest"},"fr":{"type":"string","description":"Funding rate"},"lfr":{"type":"string","description":"Last funding rate"},"o":{"type":"string","description":"24h open"},"h":{"type":"string","description":"24h high"},"l":{"type":"string","description":"24h low"},"v":{"type":"string","description":"24h volume"},"tv":{"type":"string","description":"24h turnover"},"P":{"type":"string","description":"24h change %"}}}}}}}}}}
````

## All Tickers

> Subscribe to all tickers. Same ticker structure as single ticker, but returns an array.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "allTickers" } }\
> \`\`\`\
> \
> No parameters required.<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/allTickers":{"post":{"operationId":"wsAllTickers","summary":"All Tickers","tags":["Market Data"],"description":"Subscribe to all tickers. Same ticker structure as single ticker, but returns an array.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"allTickers\" } }\n```\n\nNo parameters required.\n","responses":{"200":{"description":"Push data — same as ticker but with `tickers` array","content":{"application/json":{}}}}}}}}
````


# Explorer

## Block Data

> Subscribe to new block data.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "block" } }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/block":{"post":{"operationId":"wsBlock","summary":"Block Data","tags":["Explorer"],"description":"Subscribe to new block data.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"block\" } }\n```\n","responses":{"200":{"description":"Push data","content":{"application/json":{}}}}}}}}
````

## Block Height

> Subscribe to block height updates (lightweight).\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "blockHeight" } }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/blockHeight":{"post":{"operationId":"wsBlockHeight","summary":"Block Height","tags":["Explorer"],"description":"Subscribe to block height updates (lightweight).\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"blockHeight\" } }\n```\n","responses":{"200":{"description":"Push data","content":{"application/json":{}}}}}}}}
````

## Transactions

> Subscribe to new transactions.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "tx" } }\
> \`\`\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/tx":{"post":{"operationId":"wsTx","summary":"Transactions","tags":["Explorer"],"description":"Subscribe to new transactions.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"tx\" } }\n```\n","responses":{"200":{"description":"Push data","content":{"application/json":{}}}}}}}}
````


# User Data

## Account / Order / Position State

> Subscribe to real-time account, order, and position state updates.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "aopState", "userAddress": "0xabc..." } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| userAddress | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/aopState":{"post":{"operationId":"wsAopState","summary":"Account / Order / Position State","tags":["User Data"],"description":"Subscribe to real-time account, order, and position state updates.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"aopState\", \"userAddress\": \"0xabc...\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| userAddress | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AopStatePush"}}}}}}}},"components":{"schemas":{"AopStatePush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"sequence":{"type":"integer","description":"Sequence number"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"userAddr":{"type":"string","description":"User wallet address"},"aop":{"type":"object","properties":{"accounts":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"currency":{"type":"integer","description":"Currency code (1=USDC)"},"balance":{"type":"string","description":"Total balance"},"availableBalance":{"type":"string","description":"Available for trading"},"availableTransferBalance":{"type":"string","description":"Available for withdrawal/transfer"},"equity":{"type":"string","description":"Account equity (balance + unrealized P&L)"},"status":{"type":"string","description":"NORMAL or LIQUIDATING"},"takerFeeRatio":{"type":"string","description":"Taker fee rate"},"makerFeeRatio":{"type":"string","description":"Maker fee rate"}}}},"orders":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"ordId":{"type":"integer","description":"System order ID"},"clOrdId":{"type":"integer","description":"Client order ID"},"parentOrdId":{"type":"integer","description":"Parent order ID (TP/SL)"},"ordPx":{"type":"string","description":"Order price"},"ordQty":{"type":"string","description":"Order quantity"},"triggerPx":{"type":"string","description":"Trigger price (conditional orders)"},"ordStatus":{"type":"string","description":"NEW, PARTIALLY_FILLED, FILLED, CANCELED"},"ordType":{"type":"string","description":"LIMIT, MARKET"},"ordSide":{"type":"string","description":"BUY, SELL"},"timeInForce":{"type":"string","description":"GTC, IOC, FOK, POST_ONLY"},"reduceOnly":{"type":"string","description":"NONE, REDUCE_ONLY, TP_FROM_POSITION, SL_FROM_POSITION"},"filledQty":{"type":"string","description":"Cumulative filled quantity"},"leavesQty":{"type":"string","description":"Remaining quantity"},"cumFilledValue":{"type":"string","description":"Cumulative filled value"}}}},"positions":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbolCode":{"type":"integer","description":"Symbol code"},"symbol":{"type":"string","description":"Symbol name"},"leverage":{"type":"string","description":"Current leverage"},"longSize":{"type":"string","description":"Long position size"},"longEntryValue":{"type":"string","description":"Long position entry notional"},"shortSize":{"type":"string","description":"Short position size"},"shortEntryValue":{"type":"string","description":"Short position entry notional"},"posMode":{"type":"string","description":"ONE_WAY or HEDGE"},"posMarginMode":{"type":"string","description":"CROSS or ISOLATED"},"assignedPosBalance":{"type":"string","description":"Assigned margin (isolated mode)"},"unrealizedPnl":{"type":"string","description":"Unrealized P&L"},"cumRealizedPnl":{"type":"string","description":"Cumulative realized P&L"},"curMarkPx":{"type":"string","description":"Current mark price"},"cumTransactionFee":{"type":"string","description":"Cumulative trading fees"},"marginTableId":{"type":"integer","description":"Risk limit table ID"}}}},"settings":{"type":"array","items":{"type":"object","properties":{"symbol":{"type":"string"},"leverage":{"type":"array","description":"[posMode, leverage]"}}}}}}}}}}}}}
````

## Order History

> Subscribe to order execution history updates.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "orderHist", "userAddress": "0xabc..." } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| userAddress | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/orderHist":{"post":{"operationId":"wsOrderHist","summary":"Order History","tags":["User Data"],"description":"Subscribe to order execution history updates.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"orderHist\", \"userAddress\": \"0xabc...\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| userAddress | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderHistPush"}}}}}}}},"components":{"schemas":{"OrderHistPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"orderHists":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"ordId":{"type":"integer","description":"System order ID"},"execId":{"type":"integer","description":"Execution ID"},"clOrdId":{"type":"integer","description":"Client order ID"},"transactionTime":{"type":"integer","description":"Timestamp (ms)"},"ordType":{"type":"string","description":"LIMIT or MARKET"},"ordSide":{"type":"string","description":"BUY or SELL"},"execStatus":{"type":"string","description":"NEW, FILLED, CANCELED, PARTIALLY_FILLED"},"ordPx":{"type":"string","description":"Order price"},"execPx":{"type":"string","description":"Execution price"},"triggerPx":{"type":"string","description":"Trigger price (conditional orders)"},"execQty":{"type":"string","description":"Execution quantity"},"ordQty":{"type":"string","description":"Original order quantity"},"reduceOnly":{"type":"string","description":"NONE, REDUCE_ONLY, TP_FROM_POSITION, SL_FROM_POSITION"},"slippagePct":{"type":"string","description":"Slippage percentage"}}}}}}}}}}}
````

## User Fills

> Subscribe to user trade fill events.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "userFilled", "userAddress": "0xabc..." } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| userAddress | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/userFilled":{"post":{"operationId":"wsUserFilled","summary":"User Fills","tags":["User Data"],"description":"Subscribe to user trade fill events.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"userFilled\", \"userAddress\": \"0xabc...\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| userAddress | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserFilledPush"}}}}}}}},"components":{"schemas":{"UserFilledPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"userFills":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"ordId":{"type":"integer","description":"System order ID"},"execId":{"type":"integer","description":"Execution ID"},"ordSide":{"type":"string","description":"BUY or SELL"},"execStatus":{"type":"string","description":"FILLED, PARTIALLY_FILLED"},"ordPx":{"type":"string","description":"Order price"},"filledPx":{"type":"string","description":"Actual fill price"},"execQty":{"type":"string","description":"Fill quantity"},"ordQty":{"type":"string","description":"Original order quantity"},"ordType":{"type":"string","description":"LIMIT or MARKET"},"openFee":{"type":"string","description":"Fee for opening position"},"closeFee":{"type":"string","description":"Fee for closing position"},"posLongTerm":{"type":"integer","description":"Long position cycle identifier"},"posShortTerm":{"type":"integer","description":"Short position cycle identifier"},"txHash":{"type":"string","description":"On-chain transaction hash"},"transactionTime":{"type":"integer","description":"Timestamp (ms)"}}}}}}}}}}}
````

## Closed Position

> Subscribe to closed position events (aggregated P\&L per position cycle).\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "closedPosition", "userAddress": "0xabc..." } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| userAddress | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/closedPosition":{"post":{"operationId":"wsClosedPosition","summary":"Closed Position","tags":["User Data"],"description":"Subscribe to closed position events (aggregated P&L per position cycle).\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"closedPosition\", \"userAddress\": \"0xabc...\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| userAddress | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClosedPositionPush"}}}}}}}},"components":{"schemas":{"ClosedPositionPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"closedPositions":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbolCode":{"type":"integer","description":"Symbol code"},"symbol":{"type":"string","description":"Symbol name"},"side":{"type":"string","description":"LONG or SHORT"},"term":{"type":"integer","description":"Position cycle (increments each open from zero)"},"size":{"type":"string","description":"Total traded quantity"},"ordPx":{"type":"string","description":"Weighted avg opening price"},"closePx":{"type":"string","description":"Weighted avg closing price"},"closedPnl":{"type":"string","description":"Net P&L"},"tradingFees":{"type":"string","description":"Total trading fees"},"fundingFees":{"type":"string","description":"Cumulative funding fees"},"realisedPnl":{"type":"string","description":"Realized P&L (after fees)"},"roi":{"type":"string","description":"ROI percentage (e.g. '15.25' = 15.25%)"},"leverage":{"type":"string","description":"Max leverage during position"},"openTime":{"type":"integer","description":"Open time (ms)"},"closedTime":{"type":"integer","description":"Close time (ms)"}}}}}}}}}}}
````

## User Funding

> Subscribe to user funding fee settlement events.\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "userFunding", "userAddress": "0xabc..." } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| userAddress | string | Yes |<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/userFunding":{"post":{"operationId":"wsUserFunding","summary":"User Funding","tags":["User Data"],"description":"Subscribe to user funding fee settlement events.\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"userFunding\", \"userAddress\": \"0xabc...\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| userAddress | string | Yes |\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserFundingPush"}}}}}}}},"components":{"schemas":{"UserFundingPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"funding":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"posSize":{"type":"string","description":"Position size at settlement"},"posSide":{"type":"string","description":"LONG or SHORT"},"fundingRate":{"type":"string","description":"Applied funding rate"},"fundingFee":{"type":"string","description":"Funding fee amount (negative = paid, positive = received)"},"transactionTime":{"type":"integer","description":"Settlement timestamp (ms)"}}}}}}}}}}}
````

## User Events

> Subscribe to general user events (order acks, agent approvals, vault deposits/withdrawals).\
> \
> \`\`\`json\
> { "method": "subscribe", "subscription": { "type": "userEvent", "userAddress": "0xabc..." } }\
> \`\`\`\
> \
> \| Param | Type | Required |\
> \|-------|------|----------|\
> \| userAddress | string | Yes |\
> \
> Event types: \`perpOrder\`, \`approveAgent\`, \`actionAck\`, \`vaultDeposit\`, \`vaultWithdraw\`<br>

````json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"servers":[{"url":"wss://ws.afx.xyz/ws/dex","description":"Mainnet"},{"url":"wss://ws-testnet.afx.xyz/ws/dex","description":"Testnet"}],"paths":{"/ws/subscribe/userEvent":{"post":{"operationId":"wsUserEvent","summary":"User Events","tags":["User Data"],"description":"Subscribe to general user events (order acks, agent approvals, vault deposits/withdrawals).\n\n```json\n{ \"method\": \"subscribe\", \"subscription\": { \"type\": \"userEvent\", \"userAddress\": \"0xabc...\" } }\n```\n\n| Param | Type | Required |\n|-------|------|----------|\n| userAddress | string | Yes |\n\nEvent types: `perpOrder`, `approveAgent`, `actionAck`, `vaultDeposit`, `vaultWithdraw`\n","responses":{"200":{"description":"Push data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserEventPush"}}}}}}}},"components":{"schemas":{"UserEventPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"sequence":{"type":"integer","description":"Sequence number"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"events":{"type":"array","items":{"type":"object","properties":{"eventType":{"type":"string","description":"`perpOrder`, `approveAgent`, `actionAck`, `vaultDeposit`, `vaultWithdraw`"},"event":{"type":"array","description":"Event data (structure varies by eventType)"}}}}}}}}}}}
````


# Models

## The OrderBookPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"OrderBookPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"symbolCode":{"type":"integer","description":"Symbol code"},"symbol":{"type":"string","description":"Symbol name"},"block":{"type":"integer","description":"Block height"},"sequence":{"type":"integer","description":"Sequence number"},"depth":{"type":"integer","description":"Requested depth"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"book":{"type":"object","properties":{"bids":{"type":"array","description":"Bid levels `[price, qty]`","items":{"type":"array","items":{"type":"string"}}},"asks":{"type":"array","description":"Ask levels `[price, qty]`","items":{"type":"array","items":{"type":"string"}}}}}}}}}}}}
```

## The CandlePush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"CandlePush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"symbolName":{"type":"string","description":"Symbol name"},"timestamp":{"type":"integer","description":"Candle start time (seconds)"},"intrvl":{"type":"integer","description":"Interval (seconds)"},"open":{"type":"string","description":"Open price"},"high":{"type":"string","description":"High price"},"low":{"type":"string","description":"Low price"},"close":{"type":"string","description":"Close price"},"volume":{"type":"string","description":"Trading volume"},"turnover":{"type":"string","description":"Trading turnover (value)"},"tradeCount":{"type":"integer","description":"Number of trades"}}}}}}}}
```

## The TradesPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"TradesPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"sequence":{"type":"integer","description":"Sequence number"},"symbol":{"type":"string","description":"Symbol name"},"trades":{"type":"array","items":{"type":"object","properties":{"symbol":{"type":"string"},"ordSide":{"type":"string","description":"BUY or SELL"},"filledPx":{"type":"string","description":"Trade price"},"filledQty":{"type":"string","description":"Trade quantity"},"transactionTime":{"type":"integer","description":"Timestamp (ms)"},"txHash":{"type":"string","description":"On-chain tx hash"}}}}}}}}}}}
```

## The TickerPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"TickerPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"sequence":{"type":"integer","description":"Sequence number"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"symbol":{"type":"string","description":"Symbol name"},"ticker":{"type":"object","properties":{"s":{"type":"string","description":"Symbol"},"p":{"type":"string","description":"Last price"},"op":{"type":"string","description":"Oracle price"},"mp":{"type":"string","description":"Mark price"},"mid":{"type":"string","description":"Mid price"},"oi":{"type":"string","description":"Open interest"},"fr":{"type":"string","description":"Funding rate"},"lfr":{"type":"string","description":"Last funding rate"},"o":{"type":"string","description":"24h open"},"h":{"type":"string","description":"24h high"},"l":{"type":"string","description":"24h low"},"v":{"type":"string","description":"24h volume"},"tv":{"type":"string","description":"24h turnover"},"P":{"type":"string","description":"24h change %"}}}}}}}}}}
```

## The AopStatePush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"AopStatePush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"sequence":{"type":"integer","description":"Sequence number"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"userAddr":{"type":"string","description":"User wallet address"},"aop":{"type":"object","properties":{"accounts":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"currency":{"type":"integer","description":"Currency code (1=USDC)"},"balance":{"type":"string","description":"Total balance"},"availableBalance":{"type":"string","description":"Available for trading"},"availableTransferBalance":{"type":"string","description":"Available for withdrawal/transfer"},"equity":{"type":"string","description":"Account equity (balance + unrealized P&L)"},"status":{"type":"string","description":"NORMAL or LIQUIDATING"},"takerFeeRatio":{"type":"string","description":"Taker fee rate"},"makerFeeRatio":{"type":"string","description":"Maker fee rate"}}}},"orders":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"ordId":{"type":"integer","description":"System order ID"},"clOrdId":{"type":"integer","description":"Client order ID"},"parentOrdId":{"type":"integer","description":"Parent order ID (TP/SL)"},"ordPx":{"type":"string","description":"Order price"},"ordQty":{"type":"string","description":"Order quantity"},"triggerPx":{"type":"string","description":"Trigger price (conditional orders)"},"ordStatus":{"type":"string","description":"NEW, PARTIALLY_FILLED, FILLED, CANCELED"},"ordType":{"type":"string","description":"LIMIT, MARKET"},"ordSide":{"type":"string","description":"BUY, SELL"},"timeInForce":{"type":"string","description":"GTC, IOC, FOK, POST_ONLY"},"reduceOnly":{"type":"string","description":"NONE, REDUCE_ONLY, TP_FROM_POSITION, SL_FROM_POSITION"},"filledQty":{"type":"string","description":"Cumulative filled quantity"},"leavesQty":{"type":"string","description":"Remaining quantity"},"cumFilledValue":{"type":"string","description":"Cumulative filled value"}}}},"positions":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbolCode":{"type":"integer","description":"Symbol code"},"symbol":{"type":"string","description":"Symbol name"},"leverage":{"type":"string","description":"Current leverage"},"longSize":{"type":"string","description":"Long position size"},"longEntryValue":{"type":"string","description":"Long position entry notional"},"shortSize":{"type":"string","description":"Short position size"},"shortEntryValue":{"type":"string","description":"Short position entry notional"},"posMode":{"type":"string","description":"ONE_WAY or HEDGE"},"posMarginMode":{"type":"string","description":"CROSS or ISOLATED"},"assignedPosBalance":{"type":"string","description":"Assigned margin (isolated mode)"},"unrealizedPnl":{"type":"string","description":"Unrealized P&L"},"cumRealizedPnl":{"type":"string","description":"Cumulative realized P&L"},"curMarkPx":{"type":"string","description":"Current mark price"},"cumTransactionFee":{"type":"string","description":"Cumulative trading fees"},"marginTableId":{"type":"integer","description":"Risk limit table ID"}}}},"settings":{"type":"array","items":{"type":"object","properties":{"symbol":{"type":"string"},"leverage":{"type":"array","description":"[posMode, leverage]"}}}}}}}}}}}}}
```

## The OrderHistPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"OrderHistPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"orderHists":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"ordId":{"type":"integer","description":"System order ID"},"execId":{"type":"integer","description":"Execution ID"},"clOrdId":{"type":"integer","description":"Client order ID"},"transactionTime":{"type":"integer","description":"Timestamp (ms)"},"ordType":{"type":"string","description":"LIMIT or MARKET"},"ordSide":{"type":"string","description":"BUY or SELL"},"execStatus":{"type":"string","description":"NEW, FILLED, CANCELED, PARTIALLY_FILLED"},"ordPx":{"type":"string","description":"Order price"},"execPx":{"type":"string","description":"Execution price"},"triggerPx":{"type":"string","description":"Trigger price (conditional orders)"},"execQty":{"type":"string","description":"Execution quantity"},"ordQty":{"type":"string","description":"Original order quantity"},"reduceOnly":{"type":"string","description":"NONE, REDUCE_ONLY, TP_FROM_POSITION, SL_FROM_POSITION"},"slippagePct":{"type":"string","description":"Slippage percentage"}}}}}}}}}}}
```

## The UserFilledPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"UserFilledPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"userFills":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"ordId":{"type":"integer","description":"System order ID"},"execId":{"type":"integer","description":"Execution ID"},"ordSide":{"type":"string","description":"BUY or SELL"},"execStatus":{"type":"string","description":"FILLED, PARTIALLY_FILLED"},"ordPx":{"type":"string","description":"Order price"},"filledPx":{"type":"string","description":"Actual fill price"},"execQty":{"type":"string","description":"Fill quantity"},"ordQty":{"type":"string","description":"Original order quantity"},"ordType":{"type":"string","description":"LIMIT or MARKET"},"openFee":{"type":"string","description":"Fee for opening position"},"closeFee":{"type":"string","description":"Fee for closing position"},"posLongTerm":{"type":"integer","description":"Long position cycle identifier"},"posShortTerm":{"type":"integer","description":"Short position cycle identifier"},"txHash":{"type":"string","description":"On-chain transaction hash"},"transactionTime":{"type":"integer","description":"Timestamp (ms)"}}}}}}}}}}}
```

## The ClosedPositionPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"ClosedPositionPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"closedPositions":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbolCode":{"type":"integer","description":"Symbol code"},"symbol":{"type":"string","description":"Symbol name"},"side":{"type":"string","description":"LONG or SHORT"},"term":{"type":"integer","description":"Position cycle (increments each open from zero)"},"size":{"type":"string","description":"Total traded quantity"},"ordPx":{"type":"string","description":"Weighted avg opening price"},"closePx":{"type":"string","description":"Weighted avg closing price"},"closedPnl":{"type":"string","description":"Net P&L"},"tradingFees":{"type":"string","description":"Total trading fees"},"fundingFees":{"type":"string","description":"Cumulative funding fees"},"realisedPnl":{"type":"string","description":"Realized P&L (after fees)"},"roi":{"type":"string","description":"ROI percentage (e.g. '15.25' = 15.25%)"},"leverage":{"type":"string","description":"Max leverage during position"},"openTime":{"type":"integer","description":"Open time (ms)"},"closedTime":{"type":"integer","description":"Close time (ms)"}}}}}}}}}}}
```

## The UserFundingPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"UserFundingPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"type":{"type":"string","description":"`snapshot` or `incremental`"},"funding":{"type":"array","items":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"symbol":{"type":"string","description":"Symbol name"},"posSize":{"type":"string","description":"Position size at settlement"},"posSide":{"type":"string","description":"LONG or SHORT"},"fundingRate":{"type":"string","description":"Applied funding rate"},"fundingFee":{"type":"string","description":"Funding fee amount (negative = paid, positive = received)"},"transactionTime":{"type":"integer","description":"Settlement timestamp (ms)"}}}}}}}}}}}
```

## The UserEventPush object

```json
{"openapi":"3.0.3","info":{"title":"AFX DEX WebSocket API","version":"1.0.0"},"components":{"schemas":{"UserEventPush":{"type":"object","properties":{"channel":{"type":"string"},"data":{"type":"object","properties":{"userAddr":{"type":"string","description":"User wallet address"},"sequence":{"type":"integer","description":"Sequence number"},"timestamp":{"type":"integer","description":"Timestamp (ms)"},"events":{"type":"array","items":{"type":"object","properties":{"eventType":{"type":"string","description":"`perpOrder`, `approveAgent`, `actionAck`, `vaultDeposit`, `vaultWithdraw`"},"event":{"type":"array","description":"Event data (structure varies by eventType)"}}}}}}}}}}}
```


# Signing

EIP-712 structured signing for Agent and Master wallet operations.

AFX DEX uses [EIP-712](https://eips.ethereum.org/EIPS/eip-712) structured signatures for authentication. No API keys or sessions — every Exchange request is signed by an Ethereum wallet.

{% columns %}
{% column %}

#### Agent Signature

Used for most trading operations. The Agent wallet signs a hash derived from the **protobuf-serialized** action payload.

**Domain:** `Exchange`

**Operations:** `placeOrder`, `replaceOrder`, `placeBracketOrder`, `cancelOrder`, `cancelAll`, `setLeverage`, `setMarginMode`, `assignPosMargin`, `bindReferral`, and vault-context operations when the Agent is explicitly authorized for that vault workflow.
{% endcolumn %}

{% column %}

#### Master Signature

Used for privileged operations. The Master wallet signs the action fields **directly** as EIP-712 message — no protobuf involved.

**Domain:** `SignTransaction`

**Operations:** `approveAgent`, `revokeAgent`, `withdraw`, `faucetClaim`.
{% endcolumn %}
{% endcolumns %}

## Permission Boundary

| Operation family                                                                       | Signer                        | Operational risk                                                                                                                                          |
| -------------------------------------------------------------------------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Order placement, replacement, cancellation, leverage, margin mode, and position margin | Agent wallet                  | Can change trading exposure and liquidation risk. Cannot withdraw account funds to an external address.                                                   |
| Agent approval and revocation                                                          | Master wallet                 | Controls whether an Agent wallet can act for the Master account. Keep revocation available as an emergency runbook step.                                  |
| Account withdrawal                                                                     | Master wallet                 | Moves account funds to an external address. Never place the Master private key in an automated trading runtime.                                           |
| Vault operations                                                                       | Agent wallet in vault context | Can affect vault balances, ownership, withdrawal flow, or vault lifecycle depending on the action. Do not treat a vault-authorized Agent as trading-only. |

For operational guidance, see [Agent Safety](/api-reference/agent-safety).

***

## Agent Signing Process

{% stepper %}
{% step %}

#### Serialize action to Protobuf

Encode the action fields using the corresponding protobuf message (e.g. `MsgPlaceOrders` for placeOrder).

* JSON camelCase fields map to protobuf snake\_case
* Enum values use **integers** (e.g. `LIMIT` = `1`)
* Zero values are omitted per proto3 rules
  {% endstep %}

{% step %}

#### Compute connectionId

```
connectionId = keccak256(
    proto_bytes
    + bytes(vaultAddress)              // strip 0x, decode hex. empty if null
    + little_endian_uint64(nonce)       // 8 bytes, millisecond timestamp
    + little_endian_uint64(expiryAfter) // 8 bytes, Unix timestamp milliseconds; null → 0
)
```

`nonce` is a `uint64` request nonce. Use the current Unix timestamp in milliseconds (for example `Date.now()` or `int(time.time() * 1000)`) and do not reuse the same nonce for another signed request.

`expiryAfter` is a `uint64` Unix timestamp in milliseconds. The request expires after this timestamp. Use `null` in the request body, and `0` inside the signature payload, when the request should not expire.
{% endstep %}

{% step %}

#### Sign EIP-712

```json
{
  "types": {
    "EIP712Domain": [
      { "name": "name",              "type": "string"  },
      { "name": "version",           "type": "string"  },
      { "name": "chainId",           "type": "uint256" },
      { "name": "verifyingContract", "type": "address" }
    ],
    "Agent": [
      { "name": "source",       "type": "string"  },
      { "name": "connectionId", "type": "bytes32" }
    ]
  },
  "primaryType": "Agent",
  "domain": {
    "name":              "Exchange",
    "version":           "1",
    "chainId":           421614,
    "verifyingContract": "0x0100000000000000000000000000000000000001"
  },
  "message": {
    "source":       "b",
    "connectionId": "0x<step2_result>"
  }
}
```

| Field               | Value                                        |
| ------------------- | -------------------------------------------- |
| `source`            | `"a"` = Mainnet, `"b"` = Testnet             |
| `chainId`           | Mainnet: `42161`, Testnet: `421614`          |
| `verifyingContract` | `0x0100000000000000000000000000000000000001` |
| {% endstep %}       |                                              |
| {% endstepper %}    |                                              |

For Python applications, use the official [`afx-python-sdk`](https://github.com/afx-dex/afx-python-sdk). The SDK handles protobuf serialization, `connectionId` calculation, and EIP-712 signing internally.

```python
from afx import AfxClient

client = AfxClient.from_env(testnet=True)

# Agent-signed operations just work -- SDK handles signing internally.
result = client.exchange.place_order(
    symbol_code=1,
    px="40000",
    qty="0.5",
    side="BUY",
)
```

***

## Master Signing Process

Master wallet signs the action fields **directly** as an EIP-712 message. No protobuf serialization.

Each action has its own EIP-712 type definition. Common domain:

```json
{
  "name":              "SignTransaction",
  "version":           "1",
  "chainId":           421614,
  "verifyingContract": "0x0100000000000000000000000000000000000001"
}
```

### approveAgent

```json
{
  "ApproveAgent": [
    { "name": "dexChain",     "type": "string"  },
    { "name": "agentAddress", "type": "address" },
    { "name": "agentName",    "type": "string"  },
    { "name": "validitySeconds", "type": "uint64" },
    { "name": "nonce",        "type": "uint64"  },
    { "name": "expiryAfter",  "type": "uint64"  }
  ]
}
```

`validitySeconds` is the agent authorization duration in seconds. `0` means the authorization is valid for 7 days; maximum 365 days.

### revokeAgent

Revocation uses the same `approveAgent` signing flow with:

```json
{
  "type": "approveAgent",
  "agentAddress": "0x0000000000000000000000000000000000000000",
  "validitySeconds": 0
}
```

The Python SDK exposes this as:

```python
client.exchange.revoke_agent(agent_name="my-bot")
```

Use revocation when rotating Agent keys, stopping an automated strategy, or responding to suspected key exposure.

### withdraw

```json
{
  "Withdraw": [
    { "name": "dexChain",    "type": "string"  },
    { "name": "destination", "type": "address" },
    { "name": "amount",      "type": "string"  },
    { "name": "withdrawSequence", "type": "uint64" },
    { "name": "nonce",       "type": "uint64"  },
    { "name": "expiryAfter", "type": "uint64"  }
  ]
}
```

`withdrawSequence` is included in both the withdraw action body and the signed EIP-712 message. If omitted in the Python SDK, it defaults to the request `nonce`.

For withdrawals, use a longer `expiryAfter` window, such as current Unix time in milliseconds + 3,600,000. This gives the withdrawal enough time to pass signature verification and broadcast.

The minimum mainnet withdrawal amount is 2 USDC.

### faucetClaim (Testnet only)

```json
{
  "TestnetFaucetClaim": [
    { "name": "dexChain", "type": "string" }
  ]
}
```

Message: `{ "dexChain": "Testnet" }`, chainId fixed `421614`.

{% hint style="warning" %}
`nonce` and `expiryAfter` come from the outer request fields, not the action body. `nonce` should be the current millisecond timestamp and must not be reused. `expiryAfter` is a Unix timestamp in milliseconds; when it is `null`, use `0` in the signature.
{% endhint %}

{% hint style="info" %}
Signature `r` and `s` values must be zero-padded to exactly 32 bytes (64 hex characters). For example in Python: `"0x" + format(signed.r, "064x")`
{% endhint %}


# Agent Safety

Operational safety guidance for Master wallets, Agent wallets, and automated trading systems.

AFX separates account control from day-to-day trading by using two wallet roles.

| Wallet        | Use it for                                                                                    | Do not use it for                                                       |
| ------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Master wallet | Holding funds, approving Agents, revoking Agents, account withdrawals                         | Automated trading runtimes, bots, CI jobs, or hosted agent environments |
| Agent wallet  | Placing/canceling orders, setting leverage, margin mode, and other authorized trading actions | Account withdrawals or long-lived custody of user funds                 |

{% hint style="warning" %}
Never place the Master private key in an automated trading process. The Master wallet controls funds and Agent authorization.
{% endhint %}

## Recommended Runtime Model

1. Create a dedicated Agent wallet for each bot or strategy.
2. Approve the Agent from the Master wallet with the shortest practical validity period.
3. Store only the Agent private key in the trading runtime.
4. Query product metadata before choosing symbols, product codes, leverage, precision, or order size.
5. Keep an operational runbook for canceling orders and revoking the Agent.

## Revoke an Agent

Use revocation when rotating keys, stopping a strategy, or responding to suspected key exposure.

```python
from afx import AfxClient

client = AfxClient.from_env(testnet=True)
client.exchange.revoke_agent(agent_name="my-bot")
```

Under the hood, revocation submits an `approveAgent` action with the zero address:

```json
{
  "type": "approveAgent",
  "agentAddress": "0x0000000000000000000000000000000000000000",
  "validitySeconds": 0
}
```

## Rotate an Agent Key

1. Stop the old bot process.
2. Revoke the old Agent.
3. Create a new Agent wallet.
4. Approve the new Agent from the Master wallet.
5. Restart the bot with only the new Agent key.
6. Verify account state, open orders, and positions before resuming normal sizing.

## Vault Operations

Vault actions are not the same risk class as ordinary order placement.

| Operation area                | Safety note                                                                                                                 |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Trading on the Master account | Agent actions can change market exposure but cannot withdraw account funds to an external address.                          |
| Vault-context actions         | A vault-authorized Agent may affect vault balances, ownership, withdrawal flow, or vault lifecycle depending on the action. |
| Account withdrawals           | Master-signed operation. Keep this outside automated trading infrastructure.                                                |

Before granting automated access to vault workflows, review the exact operation and confirm the intended authority boundary for that vault.

## Testnet First

Run new agents on testnet before mainnet:

1. Claim testnet funds.
2. Approve an Agent wallet.
3. Query `GET /info/public/product-meta`.
4. Place a small limit order away from market.
5. Cancel the order.
6. Revoke or rotate the Agent if the environment was temporary.


# Python SDK

Install the official AFX Python SDK and run examples.

The official Python SDK is maintained in [`afx-dex/afx-python-sdk`](https://github.com/afx-dex/afx-python-sdk).

Use this project instead of downloading standalone SDK files from the docs. The SDK includes the generated protobuf module under `afx.protos`, so users do not need to download `dex.proto`, generate `dex_pb2.py`, or keep a local `dex_client.py`.

## Install

```bash
git clone https://github.com/afx-dex/afx-python-sdk.git
cd afx-python-sdk
python3 -m pip install -e .
```

## Configure Wallets

Private keys are loaded only from environment variables:

```bash
export AFX_MASTER_PRIVATE_KEY="0xYOUR_MASTER_PRIVATE_KEY"
export AFX_AGENT_PRIVATE_KEY="0xYOUR_AGENT_PRIVATE_KEY"
```

## Client Layout

```python
from afx import AfxClient

client = AfxClient.from_env(testnet=True)

products = client.info.get_products()
order = client.exchange.place_order(
    symbol_code=1,
    px="50000",
    qty="0.001",
    side="BUY",
    ord_type="LIMIT",
    tif="GTC",
)
```

Trading actions are under `client.exchange`, read-only queries are under `client.info`, and WebSocket helpers are under `client.websocket`.

For order requests, pass active order types such as `"LIMIT"` or `"MARKET"`. The proto default `"NONE"` and display-only `OrdType` values such as `"MARKET_LIQ_SELLOFF"`, `"LIMIT_LIQ_SELLOFF"`, `"ADL"`, and `"LIQUIDATION"` may appear in query or stream data, but they must not be used in order requests.

## Examples

Every public SDK feature has an example under the SDK repository's `examples/` directory:

```bash
python3 examples/info/get_products.py
python3 examples/exchange/place_order.py
python3 examples/exchange/replace_order.py
python3 examples/exchange/place_bracket_order.py
python3 examples/websocket/subscribe_ticker.py
```

### Example Index

**Info queries**

* [get\_products.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_products.py)
* [get\_wallet.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_wallet.py)
* [get\_orders.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_orders.py)
* [get\_positions.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_positions.py)
* [get\_kline.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_kline.py)
* [get\_agents.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_agents.py)
* [get\_active\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_active_agent.py)
* [get\_funding\_rate\_current.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/info/get_funding_rate_current.py)

**Exchange actions**

* [faucet\_claim.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/faucet_claim.py)
* [approve\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/approve_agent.py)
* [revoke\_agent.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/revoke_agent.py)
* [place\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_order.py)
* [place\_tp\_sl\_orders.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_tp_sl_orders.py)
* [replace\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/replace_order.py)
* [place\_bracket\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/place_bracket_order.py)
* [cancel\_order.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/cancel_order.py)
* [cancel\_all.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/cancel_all.py)
* [set\_leverage.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/set_leverage.py)
* [set\_margin\_mode.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/set_margin_mode.py)
* [assign\_pos\_margin.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/assign_pos_margin.py)
* [withdraw.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/withdraw.py)
* [vault\_deposit.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/vault_deposit.py)
* [vault\_withdraw.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/vault_withdraw.py)
* [bind\_referral.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/exchange/bind_referral.py)

**WebSocket and advanced usage**

* [subscribe.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe.py)
* [subscribe\_order\_book.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_order_book.py)
* [subscribe\_ticker.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_ticker.py)
* [subscribe\_account\_state.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/websocket/subscribe_account_state.py)
* [multiple\_wallets.py](https://github.com/afx-dex/afx-python-sdk/blob/main/examples/advanced/multiple_wallets.py)

## Verify

```bash
python3 -m unittest discover -s tests -v
```

The SDK tests cover signing helpers, protobuf serialization, client behavior, and example imports.


# Agent Artifacts

Machine-readable files and AI-agent entry points for AFX DEX.

AFX DEX publishes machine-readable artifacts for coding agents, SDK generators, API clients, and AI-agent trading workflows.

## API Artifacts

| Artifact                        | Repo path                                              | Public raw URL                                                                                                 |
| ------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| Combined REST OpenAPI           | `artifacts/openapi.json`                               | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/artifacts/openapi.json`                               |
| Info API OpenAPI                | `artifacts/openapi-info.json`                          | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/artifacts/openapi-info.json`                          |
| Exchange API OpenAPI            | `artifacts/openapi-exchange.json`                      | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/artifacts/openapi-exchange.json`                      |
| WebSocket AsyncAPI              | `artifacts/asyncapi.json`                              | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/artifacts/asyncapi.json`                              |
| Signed exchange envelope schema | `artifacts/schemas/signed-action-envelope.schema.json` | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/artifacts/schemas/signed-action-envelope.schema.json` |
| Signed action payload schemas   | `artifacts/schemas/signed-actions.schema.json`         | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/artifacts/schemas/signed-actions.schema.json`         |

## AI Agent Entry Points

| Agent                        | Repo path                     | Public raw URL                                                                        |
| ---------------------------- | ----------------------------- | ------------------------------------------------------------------------------------- |
| General                      | `AGENTS.md`                   | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/AGENTS.md`                   |
| Codex                        | `CODEX.md`                    | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/CODEX.md`                    |
| Claude Code                  | `CLAUDE.md`                   | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/CLAUDE.md`                   |
| OpenClaw                     | `OPENCLAW.md`                 | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/OPENCLAW.md`                 |
| LLM index                    | `llms.txt`                    | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/llms.txt`                    |
| Full LLM context             | `llms-full.txt`               | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/llms-full.txt`               |
| Paste-ready first trade task | `agent-guides/first-trade.md` | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/agent-guides/first-trade.md` |
| Agent safety guide           | `agent-safety.md`             | `https://raw.githubusercontent.com/afx-dex/afx-docs/main/agent-safety.md`             |

## Recommended Agent Flow

1. Read `llms.txt`.
2. Use the official Python or JavaScript SDK.
3. Run the first trade guide on testnet.
4. Query product metadata before choosing symbols, leverage, or quantities.
5. Keep the Master private key out of trading runtimes.
6. Cancel test orders and verify no unintended position remains.
7. Revoke or rotate temporary Agent keys.


# System Updates


# Security Incident Notice

Bridge Service Suspension

A security incident has occurred at AFX and is currently being actively addressed. The bridge service has been suspended with immediate effect. The AFX team, in coordination with leading security partners, is conducting a thorough investigation.&#x20;

**Customer Alert:** Please do **not** make any deposits to the AFX platform until the incident is fully resolved and the integrity of the system is confirmed. For the latest updates, please monitor our official Twitter account **@AFX\_XYZ** and refer to our initial announcement: <https://x.com/AFX_XYZ/status/2080126901205770734>


# Listings


# AFX New Futures Listing - BTCUSDC

Dear Users,

At 10:00 UTC on May 12, 2026, AFX has listed the new futures trading pair [BTCUSDC](https://app.afx.xyz/trade/BTCUSDC).

Tick size: 0.1

Max Leverage: 40X

For more information about the tokens, please refer to: <https://bitcoin.org/en/>

Happy Trading

The AFX Team


# AFX New Futures Listing - ETHUSDC

Dear Users,

At 10:00 UTC on May 12, 2026, AFX has listed the new futures trading pair [ETHUSDC](https://app.afx.xyz/trade/ETHUSDC).

Tick size: 0.01

Max Leverage: 40X

For more information about the tokens, please refer to: <https://ethereum.org/>

Happy Trading

The AFX Team


# Delistings


# AFX Futures Delisting - KORUUSDC

Dear Users,

At 09:00 UTC on July 15, 2026, AFX will delist the KORUUSDC perpetual futures contract.

Please close any open positions and cancel any open orders before the delisting time. After that time, KORUUSDC will no longer be available for trading.

Happy Trading

The AFX Team


# Help Center

<h2 align="center">What can we help you find?</h2>

<p align="center">Browse the topics below or use the GitBook assistant to ask anything you need help with.</p>

<p align="center"><a href="https://discord.gg/mUeDkWYENJ" class="button secondary">Contact support</a></p>


