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

# Perpetuals

> Leveraged positions on GMX V2 with up to 100x leverage

Open and manage leveraged perpetual positions on GMX V2 through natural language. Go long or short on ETH, BTC, ARB, and LINK with up to 100x leverage, all from a single prompt.

## GMX V2 on Arbitrum

GMX V2 is the dominant perpetuals DEX on Arbitrum. The `GmxV2Adapter` provides full lifecycle management for perpetual positions:

<CardGroup cols={3}>
  <Card title="Open" icon="door-open">
    Open long or short positions with configurable leverage and collateral.
  </Card>

  <Card title="Monitor" icon="chart-line">
    Track mark price, PnL, and liquidation price in real time via Chainlink feeds.
  </Card>

  <Card title="Close" icon="door-closed">
    Close positions entirely or partially with market decrease orders.
  </Card>
</CardGroup>

## Supported Markets

Each GMX V2 market is an isolated pool with its own liquidity and risk parameters.

| Market    | Index Token | Collateral | Max Leverage |
| --------- | ----------- | ---------- | ------------ |
| ETH/USDC  | ETH         | USDC       | 100x         |
| BTC/USDC  | WBTC        | USDC       | 50x          |
| ARB/USDC  | ARB         | USDC       | 50x          |
| LINK/USDC | LINK        | USDC       | 50x          |

<Info>
  All positions use USDC as collateral. The agent automatically handles the market address lookup based on the asset you mention in your prompt.
</Info>

## How Positions Work

### Opening a Position

When you request a leveraged position, the agent:

1. **Selects the market** based on the asset you mention (e.g., "go long ETH" maps to the ETH/USDC market)
2. **Fetches the current index price** from the Chainlink price feed for that market
3. **Calculates the acceptable price** with your slippage tolerance applied (higher for longs, lower for shorts)
4. **Computes the position size** in USD with 30 decimals: `collateral * leverage * 10^12`
5. **Submits a MarketIncrease order** to the GMX ExchangeRouter

The order is not executed immediately. GMX uses a keeper network that processes orders in the next block, providing MEV protection.

<Note>
  The keeper execution model means your order fills at the next-block price, not the price at submission time. The `acceptablePrice` parameter protects you from excessive slippage between submission and execution.
</Note>

### Price Feeds

The adapter reads real-time index prices from Chainlink AggregatorV3 oracles deployed on Arbitrum:

| Market    | Chainlink Feed                               |
| --------- | -------------------------------------------- |
| ETH/USDC  | `0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612` |
| BTC/USDC  | `0x6ce185860a4963106506C203335A2910413708e9` |
| ARB/USDC  | `0xb2A824043730FE05F3DA2efaFa1CBbe83fa548D6` |
| LINK/USDC | `0x86E53CF1B870786351Da77A57575e79CB55812CB` |

Chainlink returns prices with 8 decimals. The adapter normalizes these to GMX's 30-decimal format by multiplying by `10^22`.

### Closing a Position

To close a position, the agent:

1. **Reads the current position** from the GMX Reader contract using the position key
2. **Submits a MarketDecrease order** for the full position size
3. Sets the acceptable price to the extreme (0 for longs, max uint256 for shorts) to ensure the close executes

## Position Monitoring

The agent can fetch detailed position data at any time:

| Field              | Description                                      |
| ------------------ | ------------------------------------------------ |
| `size`             | Position size in USD (30 decimals)               |
| `collateral`       | Collateral amount in token decimals              |
| `entryPrice`       | Average entry price                              |
| `markPrice`        | Current mark price from Chainlink                |
| `pnl`              | Unrealized profit/loss in USD (30 decimals)      |
| `liquidationPrice` | Estimated price at which the position liquidates |

### Liquidation Price Calculation

The adapter approximates the liquidation price using the maintenance margin (1% of position size):

```
maxLoss = collateralUsd - maintenanceMargin
priceChange = maxLoss * 10^18 / sizeInTokens
liquidationPrice = entryPrice -/+ priceChange  (- for longs, + for shorts)
```

<Warning>
  Liquidation price is an approximation. The actual liquidation threshold on GMX V2 accounts for borrowing fees, funding rates, and position fees which accumulate over time and move the liquidation price closer to the mark price.
</Warning>

## Position Key

GMX V2 identifies positions by a deterministic key:

```
positionKey = keccak256(abi.encodePacked(account, market, collateralToken, isLong))
```

This means each account can hold at most one position per market per direction. Opening a new position in the same market and direction increases the existing position.

## Slippage and Risk

<CardGroup cols={2}>
  <Card title="Default Slippage" icon="sliders">
    0.50% (50 basis points). Adjustable per trade via your prompt.
  </Card>

  <Card title="Execution Fee" icon="gas-pump">
    GMX keepers require a small ETH execution fee (paid on order creation) to process your order.
  </Card>
</CardGroup>

<Warning>
  Leveraged trading carries substantial risk of loss. A 100x leveraged position can be liquidated by a 1% adverse price move. Always consider your risk tolerance and position sizing.
</Warning>

## Example Prompts

```
Open a 10x long on ETH with 500 USDC collateral
```

```
Short BTC at 20x leverage with 1000 USDC
```

```
What's my current ETH position?
```

```
Show all my open perp positions
```

```
Close my ETH long position
```

```
What's the liquidation price on my ARB short?
```

## SDK Reference

The perpetuals adapter is in the `@arb-agent/adapters` package as `GmxV2Adapter`.

### `openPosition(params)`

Opens a leveraged position. Accepts `OpenGmxPositionParams`:

| Field              | Type      | Required | Description                               |
| ------------------ | --------- | -------- | ----------------------------------------- |
| `side`             | `string`  | Yes      | `"long"` or `"short"`                     |
| `collateralToken`  | `Address` | Yes      | Collateral token address (typically USDC) |
| `collateralAmount` | `bigint`  | Yes      | Amount of collateral in token decimals    |
| `leverage`         | `number`  | Yes      | Leverage multiplier (1-100)               |
| `market`           | `Address` | No       | GMX market address (default: ETH/USDC)    |
| `slippageBps`      | `number`  | No       | Slippage tolerance (default: 50)          |

### `closePosition(market, isLong)`

Closes an entire position for the given market and direction.

### `getPosition(market, isLong)`

Returns the current position details or `null` if no position exists.

### `getPositions()`

Scans all supported markets and returns an array of all open positions.
