> ## 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.

# Roll a position

> Close a full position and open a new strike or expiry of the same option in one transaction.

This guide shows how to roll an open position into another instrument, for example a later expiry of the same call. At the end, the old position is closed and a new position is open, from one transaction.

## Before you begin

* Have an open position from the [Quickstart](https://docs.bebop.xyz/options-api/quickstart.md). The examples use its settings, `send()` helper, `ERC20_ABI`, and `FACTORY_ABI`.
* Wait until each open of the position is confirmed, about 30 seconds after it is mined. Before that, the roll quote returns `409` `PositionConfirming`.
* The new instrument must have the same underlying, option type, collateral, quote token, and Greek Factory as the position. It must be a different instrument.
* A position on a retired Greek Factory cannot roll. [Close it](https://docs.bebop.xyz/options-api/guides/close-a-position.md), then open a new position.
* A roll always uses the full remaining position. To roll part of a position, close part of it first.
* The wallet needs USDC for the close premium and ETH for gas.

**1. Find the position**

```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
)
```

**2. Choose the new instrument**

List the instruments with the same underlying and option type. Choose one where `canSell` is `true` and `factory` is the Greek Factory of the position. The example chooses the first instrument with a later expiry. Change the selection to the strike and the expiry that you want.

```python theme={null}
old = httpx.get(f"{API}/instruments", params={"instrument": position["instrument"]}).json()["instruments"][0]
page = httpx.get(
    f"{API}/instruments",
    params={"underlying": old["underlying"], "option_type": old["optionType"], "limit": 200},
).json()
new = next(
    i for i in page["instruments"]
    if i["canSell"] and i["factory"] == old["factory"] and i["expiration"] > old["expiration"]
)
```

**3. Grant the full permission mask**

A roll burns the old option tokens and mints the new option tokens in one transaction. The settlement contract needs mask `7` (`TRANSFER | MINT | BURN`). If you granted `3` and `4` before, the mask is already `7`.

```python theme={null}
ROLL_MASK = 7

greek_factory = w3.eth.contract(Web3.to_checksum_address(old["factory"]), abi=FACTORY_ABI)
granted = greek_factory.functions.permissions(account.address, SETTLEMENT).call()
if granted & ROLL_MASK != ROLL_MASK:
    send(greek_factory.functions.addPermissions(SETTLEMENT, ROLL_MASK).build_transaction({"from": account.address}))
```

**4. Approve the collateral and the USDC**

The close leg settles first, so the wallet pays the close premium before it receives the open premium.

* Approve the collateral to the Greek Factory for the new amount. For a call, the new amount is the remaining amount. For a put, it is the remaining amount times the new strike divided by the old strike, rounded down.
* Approve USDC to the settlement contract for the largest close premium that you accept, in raw units (6 decimals). For a call, the wallet must also hold that USDC.

```python theme={null}
new_amount = int(position["remainingAmount"])  # for a call
max_close_premium = 2_000_000  # 2 USDC

collateral = w3.eth.contract(Web3.to_checksum_address(new["collateral"]), abi=ERC20_ABI)
if collateral.functions.allowance(account.address, greek_factory.address).call() < new_amount:
    send(collateral.functions.approve(greek_factory.address, new_amount).build_transaction({"from": account.address}))

usdc = w3.eth.contract(Web3.to_checksum_address(new["quote"]), abi=ERC20_ABI)
if usdc.functions.allowance(account.address, SETTLEMENT).call() < max_close_premium:
    send(usdc.functions.approve(SETTLEMENT, max_close_premium).build_transaction({"from": account.address}))
```

**5. Request a roll quote**

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

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

`netPremium` is the open premium received minus the close premium paid, in raw USDC units. A negative value is a payment by the wallet. `collateralDelta` is the new collateral locked minus the collateral released. It is `"0"` for a call.

**6. Send the transaction**

Send `tx` from the wallet before `expiry`. Do not change `tx.data`.

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

**7. Verify the result**

Bebop indexes the transaction some seconds after it is mined. Then the old position has `status` `closed`, and the position with the ID `open.positionId` from the roll quote is `open`.

```python theme={null}
import time

for _ in range(30):
    response = httpx.get(f"{API}/positions/{roll['open']['positionId']}", headers=HEADERS)
    if response.status_code != 404:
        break
    time.sleep(2)
response.raise_for_status()
print(response.json()["status"])
print(httpx.get(f"{API}/positions/{roll['close']['positionId']}", headers=HEADERS).json()["status"])
```

## If it does not work

| Symptom | Cause | Correction |
| - | - | - |
| `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. |
| `400` `InvalidRoll` | The new instrument does not match the position, or it is the same instrument. | Choose a different instrument with the same underlying, option type, collateral, and Greek Factory. |
| `409` `UnsupportedFactory` | The new instrument is on a retired Greek Factory. | Choose an instrument where `canSell` is `true`. |
| `400` `MinNotional` | The new amount is below the minimum open. | For a put, choose a higher strike, or close the position. See [Limits](https://docs.bebop.xyz/options-api/reference.md#limits). |
| `409` `ExistingOptionBalance` | The wallet holds option tokens of the new instrument. | Move them out, or choose another instrument. |
| `503` `CloseMakerOffline` | A maker that holds the position is not connected. | Try again later. |
| `503` `NoValidMakerQuote` | A maker did not return a valid quote for one of the two legs. | Try again later, or choose another instrument. |
| `issues` contains `missing_factory_permissions` | The settlement contract does not have mask `7`. | Do the permission step again. |
| `issues` contains `insufficient_premium_balance` | The wallet holds less USDC than the close premium. | Add USDC to the wallet. |

## Related

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


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