# Positions

> Markdown export of the Gearbox Protocol documentation page for agents and retrieval systems.

Canonical page: https://docs.gearbox.finance/developers/gm-accounts-positions
Source file: content/developers/gm-accounts-positions.mdx
Section router: https://docs.gearbox.finance/developers/llms.txt
Section full export: https://docs.gearbox.finance/developers/llms-full.txt

Manage positions — open, adjust, close, and monitor — using the SDK vNext. The SDK builds transactions but never signs them. Your agent or wallet client handles signing and submission.

## Transaction Lifecycle

Every position action follows the same five-step flow:

| Step | Method | What Happens |
|---|---|---|
| **Prepare** | `prepareDeposit()` / `prepareOpen()` | Build a `RawTx` with calldata |
| **Preview** | `previewDeposit()` / `previewOpen()` | Simulate the transaction against current state |
| **Validate** | Check preview result | Verify HF, slippage, warnings |
| **Execute** | `walletClient.sendTransaction(rawTx)` | Sign and submit on-chain |
| **Monitor** | `sdk.accounts.getStatus()` | Track position health post-execution |

## The RawTx Type

All prepare methods return a `RawTx` — a ready-to-sign transaction object:

```typescript
interface RawTx {
  to: `0x${string}`;    // Target contract address
  calldata: `0x${string}`; // Encoded function call
  value: bigint;         // ETH value (usually 0n)
}
```

The SDK builds, never signs. You submit the transaction using your wallet client:

```typescript
const txHash = await walletClient.sendTransaction({
  to: rawTx.to,
  data: rawTx.calldata,
  value: rawTx.value,
});
```

## Depositing into a Pool

### Prepare a Deposit

```typescript
import { GearboxSDK } from "@gearbox-protocol/sdk/official";

const sdk = await GearboxSDK.init({
  chains: [1],
  startFromCache: true,
});

const rawTx = await sdk.positions.prepareDeposit({
  pool: poolAddress,
  chainId: 1,
  amount: 10_000n * 10n ** 6n, // 10,000 USDC
  receiver: walletAddress,
});
```

### Preview a Deposit

Before submitting, simulate to verify expected outcomes:

```typescript
const preview = await sdk.positions.previewDeposit({
  pool: poolAddress,
  chainId: 1,
  amount: 10_000n * 10n ** 6n,
  receiver: walletAddress,
});

console.log(`Shares received: ${preview.sharesReceived}`);
console.log(`Share price: ${preview.sharePrice}`);
console.log(`Breakeven: ${preview.breakevenDays} days`);
console.log(`Warnings: ${preview.warnings.join(", ") || "none"}`);
```

### Full Deposit Flow

```typescript
// 1. Prepare
const rawTx = await sdk.positions.prepareDeposit({
  pool: poolAddress,
  chainId: 1,
  amount: depositAmount,
  receiver: walletAddress,
});

// 2. Preview
const preview = await sdk.positions.previewDeposit({
  pool: poolAddress,
  chainId: 1,
  amount: depositAmount,
  receiver: walletAddress,
});

// 3. Validate
if (!preview.success || preview.warnings.length > 0) {
  console.error("Deposit preview failed:", preview.warnings);
  return;
}

// 4. Execute (SDK builds, you sign)
const txHash = await walletClient.sendTransaction({
  to: rawTx.to,
  data: rawTx.calldata,
  value: rawTx.value,
});
await publicClient.waitForTransactionReceipt({ hash: txHash });
```

## Opening a Leveraged Position

### Prepare an Open

```typescript
const rawTx = await sdk.positions.prepareOpen({
  creditManager: cmAddress,
  chainId: 1,
  collateralToken: wstETHAddress,
  collateralAmount: 10n * 10n ** 18n, // 10 wstETH
  targetLeverage: 3.0,
});
```

### Preview an Open

```typescript
const preview = await sdk.positions.previewOpen({
  creditManager: cmAddress,
  chainId: 1,
  collateralToken: wstETHAddress,
  collateralAmount: 10n * 10n ** 18n,
  targetLeverage: 3.0,
});

console.log(`Health Factor: ${preview.healthFactor}`);
console.log(`Net APY: ${preview.netApy}%`);
console.log(`Actual leverage: ${preview.actualLeverage}x`);
console.log(`Debt: ${preview.debtAmount}`);
console.log(`Swap impact: ${preview.swapImpactBps} bps`);
```

### Full Open Flow

```typescript
// 1. Prepare the transaction
const rawTx = await sdk.positions.prepareOpen({
  creditManager: cmAddress,
  chainId: 1,
  collateralToken: wstETHAddress,
  collateralAmount: collateralAmount,
  targetLeverage: 3.0,
});

// 2. Preview and validate
const preview = await sdk.positions.previewOpen({
  creditManager: cmAddress,
  chainId: 1,
  collateralToken: wstETHAddress,
  collateralAmount: collateralAmount,
  targetLeverage: 3.0,
});

if (!preview.success) {
  console.error("Position open failed simulation");
  return;
}

if (preview.healthFactor < 1.5) {
  console.warn(`Health factor ${preview.healthFactor} is below safety threshold`);
  return;
}

if (preview.warnings.length > 0) {
  console.warn("Warnings:", preview.warnings);
}

// 3. Execute
const txHash = await walletClient.sendTransaction({
  to: rawTx.to,
  data: rawTx.calldata,
  value: rawTx.value,
});
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
console.log(`Position opened: ${receipt.transactionHash}`);
```

## Universal Transaction Preview

Use `sdk.previewTransaction()` to simulate any raw transaction against current chain state. This works for transactions built outside the SDK as well.

```typescript
const result = await sdk.previewTransaction({
  to: targetAddress,
  calldata: encodedCalldata,
  value: 0n,
}, {
  chainId: 1,
  from: walletAddress,
});

console.log(`Success: ${result.success}`);
console.log(`Health factor: ${result.healthFactor}`);
console.log(`Actions: ${result.actions.map(a => a.type).join(", ")}`);
console.log(`Balance changes:`, result.balanceChanges);
console.log(`Warnings: ${result.warnings.join(", ") || "none"}`);
```

### Preview Result Fields

| Field | Type | Description |
|---|---|---|
| `success` | `boolean` | Whether the simulation succeeded |
| `healthFactor` | `number \| null` | Projected health factor after execution |
| `actions` | `Action[]` | Decoded actions the transaction performs |
| `balanceChanges` | `BalanceChange[]` | Token balance deltas |
| `warnings` | `string[]` | Human-readable risk warnings |

## Listing Credit Accounts

Retrieve all credit accounts owned by a wallet:

```typescript
const accounts = await sdk.accounts.list({
  owner: walletAddress,
  chainId: 1,
});

for (const account of accounts) {
  console.log(`Account: ${account.address}`);
  console.log(`  CM: ${account.creditManager}`);
  console.log(`  Health Factor: ${account.healthFactor}`);
  console.log(`  Total Value: $${account.totalValueUsd}`);
}
```

## Position Health and Status

Get detailed status for a specific credit account:

```typescript
const status = await sdk.accounts.getStatus({
  account: creditAccountAddress,
  chainId: 1,
});

console.log(`Health Factor: ${status.healthFactor}`);
console.log(`Leverage: ${status.leverage}x`);
console.log(`Total Value: $${status.totalValueUsd}`);
console.log(`Total Debt: $${status.totalDebtUsd}`);

// Token composition
for (const token of status.tokens) {
  console.log(`  ${token.symbol}: ${token.balance} ($${token.valueUsd})`);
}

// Active bots
for (const bot of status.bots) {
  console.log(`  Bot: ${bot.address} — ${bot.permissions.join(", ")}`);
}
```

### Status Fields

| Field | Type | Description |
|---|---|---|
| `healthFactor` | `number` | Current HF. Below 1 means liquidatable |
| `totalValueUsd` | `number` | Position total value in USD |
| `totalDebtUsd` | `number` | Outstanding debt in USD |
| `leverage` | `number` | Current leverage ratio |
| `tokens` | `TokenPosition[]` | Per-token balances, values, and LT info |
| `bots` | `BotInfo[]` | Attached bots and their permissions |
| `isPaused` | `boolean` | Whether the credit manager is paused |
| `expirationDate` | `string \| null` | Account expiration, if applicable |

## Monitoring Alerts

Use `sdk.monitor.getAlerts()` to check for active warnings on your positions:

```typescript
const alerts = await sdk.monitor.getAlerts({
  owner: walletAddress,
  chainId: 1,
});

for (const alert of alerts) {
  console.log(`[${alert.severity}] ${alert.account}: ${alert.message}`);
}
```

### Alert Types

| Severity | Condition | Suggested Action |
|---|---|---|
| `"warning"` | Health factor below 1.3 | Add collateral or reduce debt |
| `"critical"` | Health factor below 1.1 | Immediate deleveraging or exit |
| `"info"` | LT ramp active | Plan scheduled adjustment |
| `"info"` | Account nearing expiration | Close or migrate before deadline |

## Position Lifecycle Example

A complete flow from discovery through monitoring:

```typescript
import { GearboxSDK, Asset } from "@gearbox-protocol/sdk/official";

// 1. Initialize
const sdk = await GearboxSDK.init({ chains: [1], startFromCache: true });

// 2. Discover
const strategies = await sdk.strategies.list({
  chainId: 1,
  asset: Asset.ETH,
  minNetApy: 3,
});
const strategy = strategies[0];

// 3. Prepare
const rawTx = await sdk.positions.prepareOpen({
  creditManager: strategy.id,
  chainId: 1,
  collateralToken: wstETHAddress,
  collateralAmount: 10n * 10n ** 18n,
  targetLeverage: 3.0,
});

// 4. Preview
const preview = await sdk.positions.previewOpen({
  creditManager: strategy.id,
  chainId: 1,
  collateralToken: wstETHAddress,
  collateralAmount: 10n * 10n ** 18n,
  targetLeverage: 3.0,
});

if (!preview.success || preview.healthFactor < 1.5) {
  throw new Error("Preview failed safety checks");
}

// 5. Execute (you sign)
const txHash = await walletClient.sendTransaction({
  to: rawTx.to,
  data: rawTx.calldata,
  value: rawTx.value,
});
await publicClient.waitForTransactionReceipt({ hash: txHash });

// 6. Monitor
const accounts = await sdk.accounts.list({ owner: walletAddress, chainId: 1 });
const status = await sdk.accounts.getStatus({
  account: accounts[0].address,
  chainId: 1,
});
console.log(`Position HF: ${status.healthFactor}`);
```

## Method Reference

| Method | Returns | Description |
|---|---|---|
| `sdk.positions.prepareDeposit(params)` | `RawTx` | Build a pool deposit transaction |
| `sdk.positions.previewDeposit(params)` | `DepositPreview` | Simulate a pool deposit |
| `sdk.positions.prepareOpen(params)` | `RawTx` | Build a leveraged position open |
| `sdk.positions.previewOpen(params)` | `OpenPreview` | Simulate a position open |
| `sdk.previewTransaction(rawTx, opts)` | `TransactionPreview` | Universal simulation for any raw tx |
| `sdk.accounts.list(params)` | `CreditAccount[]` | List credit accounts for a wallet |
| `sdk.accounts.getStatus(params)` | `AccountStatus` | Full position health and composition |
| `sdk.monitor.getAlerts(params)` | `Alert[]` | Active warnings across positions |

## Learn More

- [Opportunities](https://docs.gearbox.finance/developers/gm-markets-opportunities) — discovering pools and strategies
- [History & Events](https://docs.gearbox.finance/developers/gm-markets-history) — historical data and parameter change tracking
- [Account Operations](https://docs.gearbox.finance/developers/gm-accounts-ops) — low-level multicall operations reference
- [Multicalls](https://docs.gearbox.finance/developers/gm-accounts-multicalls) — building complex multi-step transactions
