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

# Close a position

> Buy back the option tokens of an open position before expiry and get the collateral back.

This guide shows how to close all or part of an open position before expiry. At the end, the wallet has paid the close premium in USDC and has the collateral back.

## Before you begin

* Complete the [Quickstart](https://docs.bebop.xyz/options-api/quickstart.md). The examples use its settings, `send()` helper, `ERC20_ABI`, and `FACTORY_ABI`.
* The position must be `open`, and the wallet must hold at least as many receipt tokens (RT) as you close.
* Wait until the open is confirmed, about 30 seconds after it is mined. Before that, a full close quote returns `409` `PositionConfirming`.
* Request the close quote more than 30 seconds before `expiration`. After that, Bebop does not quote the instrument.
* The wallet needs USDC for the premium and ETH for gas.

**1. Find the position**

List the positions of the API key and choose the open position of the wallet. If you have more than 200 positions, read the next pages with `nextCursor`.

```python theme={null}
positions = httpx.get(f"{API}/positions", headers=HEADERS, params={"limit": 200}).json()["positions"]
position = next(
    p for p in positions
    if p["takerAddress"].lower() == account.address.lower()
    and p["status"] == "open"
    and int(p["remainingAmount"]) > 0
)
print(position["positionId"], position["instrument"], position["remainingAmount"])
```

**2. Grant the settlement contract the burn permission**

Add mask `4` (`BURN`) for the settlement contract on the Greek Factory of the instrument. With this permission, the trade burns the returned option tokens together with the wallet's RT and releases the collateral.

```python theme={null}
BURN_MASK = 4

instrument = httpx.get(f"{API}/instruments", params={"instrument": position["instrument"]}).json()["instruments"][0]
greek_factory = w3.eth.contract(Web3.to_checksum_address(instrument["factory"]), abi=FACTORY_ABI)
granted = greek_factory.functions.permissions(account.address, SETTLEMENT).call()
if granted & BURN_MASK != BURN_MASK:
    send(greek_factory.functions.addPermissions(SETTLEMENT, BURN_MASK).build_transaction({"from": account.address}))
```

**3. Approve USDC to the settlement contract**

The settlement contract takes the close premium from the wallet. Approve the largest premium that you accept, in raw USDC units (6 decimals).

```python theme={null}
max_premium = 2_000_000  # 2 USDC
usdc = w3.eth.contract(Web3.to_checksum_address(instrument["quote"]), abi=ERC20_ABI)
if usdc.functions.allowance(account.address, SETTLEMENT).call() < max_premium:
    send(usdc.functions.approve(SETTLEMENT, max_premium).build_transaction({"from": account.address}))
```

**4. Request a close quote**

To close the full position, omit `amount`. To close part of it, set `amount` in raw option-token units. The `amount` must be at or above the [minimum amount](https://docs.bebop.xyz/options-api/reference.md#limits). The remainder must also be at or above the minimum, unless `amount` is the full RT balance of the wallet.

```bash bash theme={null}
curl --get "https://api.bebop.xyz/options/ethereum/v1/positions/POSITION_ID/quote" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  --data-urlencode "validate=true"
```

```python python theme={null}
response = httpx.get(
    f"{API}/positions/{position['positionId']}/quote",
    headers=HEADERS,
    params={"validate": "true"},
)
response.raise_for_status()
quote = response.json()
if quote["issues"]:
    raise RuntimeError(f"wallet not ready: {quote['issues']}")
if int(quote["premium"]) > max_premium:
    raise RuntimeError(f"premium {quote['premium']} is above the limit")
```

For a close, `premium` is the total USDC that the wallet pays, including the Bebop `fee`.

**5. Send the transaction**

> [!WARNING]
>
> Do not move RT out of the wallet between the quote and the transaction. The transaction can then succeed with less RT burned and less collateral returned.

Send `tx` from the wallet before `expiry`.

```python theme={null}
send({
    "to": Web3.to_checksum_address(quote["tx"]["to"]),
    "data": quote["tx"]["data"],
    "value": int(quote["tx"]["value"]),
})
```

**6. Verify the result**

Read the position again until `closedAmount` shows the close. Bebop indexes the transaction some seconds after it is mined.

```python theme={null}
import time

closed_before = int(position["closedAmount"])
for _ in range(30):
    position = httpx.get(f"{API}/positions/{position['positionId']}", headers=HEADERS).json()
    if int(position["closedAmount"]) > closed_before:
        break
    time.sleep(2)
print(position["status"], position["closedAmount"], position["remainingAmount"], position["rtBalance"])
```

After a full close, `status` is `closed`, `remainingAmount` is `"0"`, and `rtBalance` is `"0"`. After a partial close, `status` stays `open`. The collateral is back in the wallet.

## If it does not work

| Symptom | Cause | Correction |
| - | - | - |
| `409` `InsufficientReceiptBalance` | The wallet holds less RT than the close amount. | Close a smaller amount, or move the RT back to the wallet. |
| `409` `PositionConfirming` | An open of the position is not confirmed yet. | Wait about 30 seconds after the open, then try again. |
| `404` `PositionNotFound` | The position is fully closed. | Read the position to see its status. |
| `409` `InsufficientPositionAmount` | The amount is more than the confirmed remainder. | Close a smaller amount. |
| `400` `MinNotional` | The amount, or the remainder, is below the minimum. | Change the amount, or close the full position. |
| `503` `CloseMakerOffline` | A maker that holds this position is not connected. | Try again later. |
| `409` `CloseQuoteInvalidated` | The position changed while Bebop created the quote. | Request a new quote. |
| `issues` contains `missing_factory_permissions` | The settlement contract does not have mask `4`. | Do the permission step again. |
| `issues` contains `insufficient_premium_allowance` | The USDC allowance is less than `premium`. | Approve a larger amount. |
| `issues` contains `insufficient_premium_balance` | The wallet holds less USDC than `premium`. | Add USDC to the wallet. |

## Related

* [Roll a position](https://docs.bebop.xyz/options-api/guides/roll-a-position.md)
* [How options settle](https://docs.bebop.xyz/options-api/how-options-settle.md#close-buy-to-close)
* [Close quote reference](https://docs.bebop.xyz/options-api/reference.md#request-a-close-quote)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.