> For the complete documentation index, see [llms.txt](https://docs.aqua.network/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aqua.network/developers/concentrated-liquidity/managing-positions-code-examples.md). Agents can also search and read this documentation through its [MCP server](https://docs.aqua.network/~gitbook/mcp).

# Managing positions: code examples

Code examples for the full concentrated liquidity position lifecycle: reading pool state, opening a position, monitoring it, claiming fees and rewards, and withdrawing.

This page walks through the full lifecycle of a concentrated liquidity position with the [official SDKs](https://docs.aqua.network/developers/integrating-with-aquarius.md#official-sdks) (0.6.0 or later). Amounts and liquidity always come from the contract's own estimators — the SDK converts prices to ticks with exact integer math and derives every slippage guard from a quote, never from client-side arithmetic.

{% hint style="info" %}
The [complete code examples](#complete-code-examples) run the whole lifecycle in one script. The [contract-level flow](#contract-level-flow-any-language) at the bottom points to the pool functions for other languages; per-function signatures live in the [contract interface reference](https://docs.aqua.network/developers/concentrated-liquidity/contract-interface-reference.md). The concentrated surface is beta: the contracts are under an external audit.
{% endhint %}

### Step 1. Set up and find a concentrated pool

{% tabs %}
{% tab title="Python" %}

```python
from stellar_sdk import Keypair
from aquarius import AquariusClient, Asset, XLM

AQUA = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA")

aqua = AquariusClient(network="mainnet", signer=Keypair.from_secret("S..."))

pool = next(p for p in aqua.pools_for_pair(XLM, AQUA) if p.type == "concentrated")

print(pool.slot0())          # Slot0(sqrt_price_x96=..., tick=...)
print(pool.tick_spacing())   # 20 (0.1% pool), 60 (0.3%) or 200 (1.0%)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import { Keypair } from "@stellar/stellar-sdk";
import { AquariusClient, Asset, XLM } from "@aquariusdefi/sdk";

const AQUA = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA");

const aqua = new AquariusClient({ network: "mainnet", signer: Keypair.fromSecret("S...") });

const pool = (await aqua.pools.forPair(XLM, AQUA)).find(p => p.type === "concentrated");

console.log(await pool.slot0());         // { sqrtPriceX96: ..., tick: ... }
console.log(await pool.tickSpacing());   // 20 (0.1% pool), 60 (0.3%) or 200 (1.0%)
```

{% endtab %}
{% endtabs %}

### Step 2. Convert your price range to ticks

Prices are token1 per token0 in base units. `tick_from_price` is integer-exact and identical across both SDKs; `snap_tick` aligns a tick to the pool's spacing. Passing `price_range` to the estimator in the next step performs both conversions for you:

{% tabs %}
{% tab title="Python" %}

```python
from aquarius import price_at_tick, snap_tick, tick_from_price

spacing = pool.tick_spacing()
tick = pool.current_tick()

# Range: 5% below to 5% above the current price
lower = snap_tick(tick_from_price(price_at_tick(tick) * 0.95), spacing)
upper = snap_tick(tick_from_price(price_at_tick(tick) * 1.05), spacing, up=True)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import { priceAtTick, snapTick, tickFromPrice } from "@aquariusdefi/sdk";

const spacing = await pool.tickSpacing();
const tick = await pool.currentTick();

// Range: 5% below to 5% above the current price
const lower = snapTick(tickFromPrice(priceAtTick(tick) * 0.95), spacing);
const upper = snapTick(tickFromPrice(priceAtTick(tick) * 1.05), spacing, { up: true });
```

{% endtab %}
{% endtabs %}

### Step 3. Estimate and open the position

Deposits are two-phase: `estimate_position_deposit` quotes through the contract's own estimator, then `execute` runs the deposit with a minimum-liquidity guard derived from that quote. The contract pulls the desired amounts and refunds whatever the range does not need:

{% tabs %}
{% tab title="Python" %}

```python
est = pool.estimate_position_deposit(
    {XLM: 10_0000000, AQUA: 5000_0000000},
    tick_range=(lower, upper),          # or price_range=(low, high)
)
print(f"will use: {est.amounts}, minting ~{est.liquidity} liquidity")

position = est.execute(slippage=0.01)   # min-liquidity guard from the estimate
print(f"opened with {position.liquidity} liquidity  {position.tx_hash}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const est = await pool.estimatePositionDeposit({
  amounts: [[XLM, 10_0000000n], [AQUA, 5000_0000000n]],
  tickRange: [lower, upper],            // or priceRange: [low, high]
});
console.log(`will use: ${est.amounts}, minting ~${est.liquidity} liquidity`);

const position = await est.execute({ slippage: 0.01 });   // min-liquidity guard from the estimate
console.log(`opened with ${position.liquidity} liquidity  ${position.txHash}`);
```

{% endtab %}
{% endtabs %}

A position is the key `(owner, tick_lower, tick_upper)` — no NFTs, merged on re-deposit, at most 20 ranges per account.

### Step 4. List your positions and check if they are in range

`position_range_status` matches the contract's active-liquidity rule exactly: the range is half-open `[tick_lower, tick_upper)`, so a position sitting at `tick_upper` is already out and earning nothing. "Below" means the price is under the range and the position sits entirely in the first sorted token; "above" — entirely in the second:

{% tabs %}
{% tab title="Python" %}

```python
for tick_lower, tick_upper in pool.position_ranges():
    status = pool.position_range_status(tick_lower, tick_upper)
    print(f"[{tick_lower}, {tick_upper}): {status.status}")   # in_range | below | above

value = pool.position_value(lower, upper)
print(f"principal: {value.principal}, fees: {value.fees}, total: {value.total}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
for (const [tickLower, tickUpper] of await pool.positionRanges()) {
  const status = await pool.positionRangeStatus(tickLower, tickUpper);
  console.log(`[${tickLower}, ${tickUpper}): ${status.status}`);   // in_range | below | above
}

const value = await pool.positionValue(lower, upper);
console.log(`principal: ${value.principal}, fees: ${value.fees}, total: ${value.total}`);
```

{% endtab %}
{% endtabs %}

### Step 5. Check and claim swap fees

Fees accrue per position while it is in range. Withdrawals auto-claim the position's fees, so explicit claims are for harvesting without touching the principal.

The steps from here on each follow another write on the same pool. A claim or withdrawal simulated on the ledger that applied the previous write can fail on-chain once rewards accrue, so each one first waits for the next ledger with `wait_for_next_ledger()` (`waitForNextLedger()` in JavaScript):

{% tabs %}
{% tab title="Python" %}

```python
print(pool.position_fees(lower, upper))     # accrued, unclaimed, in sorted-token order

aqua.wait_for_next_ledger()                 # past the ledger of the previous write
claimed = pool.claim_position_fees(lower, upper)
print(f"claimed: {claimed.amounts}  {claimed.tx_hash}")

# Or across all of the signer's positions in this pool:
aqua.wait_for_next_ledger()
pool.claim_all_position_fees()
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
console.log(await pool.positionFees(lower, upper));   // accrued, unclaimed, in sorted-token order

await aqua.waitForNextLedger();                       // past the ledger of the previous write
const claimed = await pool.claimPositionFees(lower, upper);
console.log(`claimed: ${claimed.amounts}  ${claimed.txHash}`);

// Or across all of the signer's positions in this pool:
await aqua.waitForNextLedger();
await pool.claimAllPositionFees();
```

{% endtab %}
{% endtabs %}

### Step 6. Claim AQUA rewards

Reward accrual and claims work the same as for every other pool type:

{% tabs %}
{% tab title="Python" %}

```python
print(pool.pending_rewards())        # accrued AQUA, stroops

aqua.wait_for_next_ledger()
claim = pool.claim_rewards()
print(f"claimed {claim.amount} AQUA  {claim.tx_hash}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
console.log(await pool.pendingRewards());   // accrued AQUA, stroops

await aqua.waitForNextLedger();
const claim = await pool.claimRewards();
console.log(`claimed ${claim.amount} AQUA  ${claim.txHash}`);
```

{% endtab %}
{% endtabs %}

### Step 7. Withdraw the position

Partial or full — pass the liquidity to remove, or nothing for the whole position. Per-token minimums come from a simulation of this exact withdrawal, reduced by `slippage`; the payout includes the position's accrued fees:

{% tabs %}
{% tab title="Python" %}

```python
aqua.wait_for_next_ledger()
half = pool.withdraw_position(lower, upper, position.liquidity // 2)

aqua.wait_for_next_ledger()
closed = pool.withdraw_position(lower, upper)     # full close
print(f"received: {closed.amounts}  {closed.tx_hash}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
await aqua.waitForNextLedger();
const half = await pool.withdrawPosition({ tickLower: lower, tickUpper: upper, liquidity: position.liquidity / 2n });

await aqua.waitForNextLedger();
const closed = await pool.withdrawPosition({ tickLower: lower, tickUpper: upper });   // full close
console.log(`received: ${closed.amounts}  ${closed.txHash}`);
```

{% endtab %}
{% endtabs %}

## Complete code examples

The scripts below run the whole lifecycle from Steps 1–7 in one go on the Stellar mainnet: they find the XLM/AQUA concentrated pool, open a position 5% below to 5% above the current price, check its range status, claim its swap fees and AQUA rewards, and withdraw it in full.

To execute the code, provide the secret key of a Stellar account with at least 15 XLM and 5,000 AQUA. Save the JavaScript version as a `.mjs` file: it uses top-level `await`.

<details>

<summary>Copy the full code Python</summary>

```python
from stellar_sdk import Keypair
from aquarius import AquariusClient, Asset, XLM, price_at_tick, snap_tick, tick_from_price

# =========================================
# Configuration & Setup
# =========================================

# This account must hold at least 15 XLM and 5,000 AQUA.
user_secret_key = "S..."

# The pair of the concentrated pool
token_a = XLM
token_b = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA")

# Amounts you offer, in stroops; the contract uses what the range needs and refunds the rest
desired_amounts = {token_a: 10_0000000, token_b: 5000_0000000}

# Price range: 5% below to 5% above the current price
range_width = 0.05

# Slippage tolerance: 1%
slippage = 0.01

aqua = AquariusClient(network="mainnet", signer=Keypair.from_secret(user_secret_key))

# =========================================
# Position Lifecycle
# =========================================

# Step 1. Find the concentrated pool and read its state
pool = next(p for p in aqua.pools_for_pair(token_a, token_b) if p.type == "concentrated")
slot0 = pool.slot0()
spacing = pool.tick_spacing()
print(f"pool {pool.address}: tick={slot0.tick} spacing={spacing}")

# Step 2. Convert the price range to ticks
price = price_at_tick(slot0.tick)
tick_lower = snap_tick(tick_from_price(price * (1 - range_width)), spacing)
tick_upper = snap_tick(tick_from_price(price * (1 + range_width)), spacing, up=True)
print(f"range: [{tick_lower}, {tick_upper})")

# Step 3. Estimate and open the position
estimate = pool.estimate_position_deposit(desired_amounts, tick_range=(tick_lower, tick_upper))
print(f"estimate: uses {estimate.amounts}, mints ~{estimate.liquidity} liquidity")

position = estimate.execute(slippage=slippage)
print(f"deposited {position.amounts}, received liquidity {position.liquidity}")
print(f"transaction: {position.tx_hash}")

# Step 4. List positions and check whether they are in range
for lower, upper in pool.position_ranges():
    status = pool.position_range_status(lower, upper)
    print(f"position [{lower}, {upper}): {status.status}")

value = pool.position_value(tick_lower, tick_upper)
print(f"principal: {value.principal}, fees: {value.fees}, total: {value.total}")

# Step 5. Check and claim swap fees
# Each write below follows another write on the same pool, so it waits for the next ledger first.
print(f"pending fees: {pool.position_fees(tick_lower, tick_upper)}")
aqua.wait_for_next_ledger()
fees = pool.claim_position_fees(tick_lower, tick_upper)
print(f"claimed fees: {fees.amounts}  {fees.tx_hash}")

# Step 6. Check and claim AQUA rewards
print(f"pending AQUA reward: {pool.pending_rewards() / 1e7}")
aqua.wait_for_next_ledger()
rewards = pool.claim_rewards()
print(f"claimed AQUA reward: {rewards.amount / 1e7}  {rewards.tx_hash}")

# Step 7. Withdraw the whole position (principal and accrued fees)
aqua.wait_for_next_ledger()
withdrawn = pool.withdraw_position(tick_lower, tick_upper, slippage=slippage)
print(f"withdrawn: {withdrawn.amounts}  {withdrawn.tx_hash}")
```

</details>

<details>

<summary>Copy the full code JavaScript</summary>

```javascript
import { Keypair } from "@stellar/stellar-sdk";
import { AquariusClient, Asset, XLM, priceAtTick, snapTick, tickFromPrice } from "@aquariusdefi/sdk";

// =========================================
// Configuration & Setup
// =========================================

// This account must hold at least 15 XLM and 5,000 AQUA.
const userSecretKey = "S...";

// The pair of the concentrated pool
const tokenA = XLM;
const tokenB = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA");

// Amounts you offer, in stroops; the contract uses what the range needs and refunds the rest
const desiredAmounts = [[tokenA, 10_0000000n], [tokenB, 5000_0000000n]];

// Price range: 5% below to 5% above the current price
const rangeWidth = 0.05;

// Slippage tolerance: 1%
const slippage = 0.01;

const aqua = new AquariusClient({ network: "mainnet", signer: Keypair.fromSecret(userSecretKey) });

// =========================================
// Position Lifecycle
// =========================================

// Step 1. Find the concentrated pool and read its state
const pool = (await aqua.pools.forPair(tokenA, tokenB)).find(p => p.type === "concentrated");
const slot0 = await pool.slot0();
const spacing = await pool.tickSpacing();
console.log(`pool ${pool.address}: tick=${slot0.tick} spacing=${spacing}`);

// Step 2. Convert the price range to ticks
const price = priceAtTick(slot0.tick);
const tickLower = snapTick(tickFromPrice(price * (1 - rangeWidth)), spacing);
const tickUpper = snapTick(tickFromPrice(price * (1 + rangeWidth)), spacing, { up: true });
console.log(`range: [${tickLower}, ${tickUpper})`);

// Step 3. Estimate and open the position
const estimate = await pool.estimatePositionDeposit({ amounts: desiredAmounts, tickRange: [tickLower, tickUpper] });
console.log(`estimate: uses ${estimate.amounts}, mints ~${estimate.liquidity} liquidity`);

const position = await estimate.execute({ slippage });
console.log(`deposited ${position.amounts}, received liquidity ${position.liquidity}`);
console.log(`transaction: ${position.txHash}`);

// Step 4. List positions and check whether they are in range
for (const [lower, upper] of await pool.positionRanges()) {
  const status = await pool.positionRangeStatus(lower, upper);
  console.log(`position [${lower}, ${upper}): ${status.status}`);
}

const value = await pool.positionValue(tickLower, tickUpper);
console.log(`principal: ${value.principal}, fees: ${value.fees}, total: ${value.total}`);

// Step 5. Check and claim swap fees
// Each write below follows another write on the same pool, so it waits for the next ledger first.
console.log(`pending fees: ${await pool.positionFees(tickLower, tickUpper)}`);
await aqua.waitForNextLedger();
const fees = await pool.claimPositionFees(tickLower, tickUpper);
console.log(`claimed fees: ${fees.amounts}  ${fees.txHash}`);

// Step 6. Check and claim AQUA rewards
console.log(`pending AQUA reward: ${Number(await pool.pendingRewards()) / 1e7}`);
await aqua.waitForNextLedger();
const rewards = await pool.claimRewards();
console.log(`claimed AQUA reward: ${Number(rewards.amount) / 1e7}  ${rewards.txHash}`);

// Step 7. Withdraw the whole position (principal and accrued fees)
await aqua.waitForNextLedger();
const withdrawn = await pool.withdrawPosition({ tickLower, tickUpper, slippage });
console.log(`withdrawn: ${withdrawn.amounts}  ${withdrawn.txHash}`);
```

</details>

## Contract-level flow (any language)

The same lifecycle at the contract level is outlined in [Typical position lifecycle](https://docs.aqua.network/developers/concentrated-liquidity.md#typical-position-lifecycle), and the price-to-tick conversion in [Prices and ticks](https://docs.aqua.network/developers/concentrated-liquidity.md#prices-and-ticks). Each step calls the pool contract directly: `estimate_deposit_position` and `deposit_position` to open, `withdraw_position`, `claim_position_fees`, and `claim_all_position_fees` to manage the position, and the router's `claim` for AQUA rewards. The steps read state with `get_slot0` and `get_tick_spacing` (the pool), `get_user_position_snapshot` (your positions), `get_position_fees` (pending swap fees), `get_user_reward` (pending AQUA rewards), and `estimate_withdraw_position` (the amounts a withdrawal returns, to derive `min_amounts`). Signatures and parameters are in the [contract interface reference](https://docs.aqua.network/developers/concentrated-liquidity/contract-interface-reference.md), and the authorization tree of each write in [Contract authorization](https://docs.aqua.network/developers/reference/contract-authorization.md#authorization-trees).
