> For the complete documentation index, see [llms.txt](https://docs.outpoll.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/protect-open-positions.md).

# Protect Open Positions

Put an entire-position stop-loss and take-profit on every open position that has none.

Use this script to make sure no position is left without protection.

## What This Script Does

* Loads the open positions that have no TP/SL level.
* Calculates take-profit at `10%` and stop-loss at `5%` from the entry price, on the right side for `LONG` and `SHORT`.
* Adds one entire-position `SL` and one `TP` level per position.
* Skips a level the API refuses, for example when the price has already moved past it.

Start with [Setup & Helpers](broken://pages/5f82d3397698cce89dbce1b8ec851e2c9aceba84) if you still need the shared prerequisites.

{% code title="protect\_positions.py" %}

```python
#!/usr/bin/env python3
"""Put an entire-position stop loss and take profit on every open position that has none."""
import time
from decimal import Decimal

from futures_helpers import FuturesClient, FuturesApiError, get_pairs, round_price

API_KEY = "your-api-key"
API_SECRET = "your-api-secret"

TP_PCT = Decimal("0.10")   # take profit 10% from entry
SL_PCT = Decimal("0.05")   # stop loss 5% from entry
PAUSE = 3.5                # seconds between calls — stay inside your key's rate limit

client = FuturesClient(API_KEY, API_SECRET)
pairs = {p["gid"]: p for p in get_pairs().values()}

# Step 1 — Open positions without any TP/SL level
positions = client.get("/api/v1/positions", params={"tpsl": "without"})
if not positions:
    raise SystemExit("every open position already has TP/SL")

for pos in positions:
    tick = pairs[pos["pi"]]["ts"]
    long = pos["s"] == "LONG"
    tp = round_price(pos["e"] * (1 + TP_PCT if long else 1 - TP_PCT), tick)
    sl = round_price(pos["e"] * (1 - SL_PCT if long else 1 + SL_PCT), tick)
    print(f"{pairs[pos['pi']]['nm']} {pos['s']} {pos['sz']} @ {pos['e']}  →  TP {tp}  SL {sl}")

    # Step 2 — One entire-position level of each type (re-sending the same price is a no-op)
    for kind, price in (("SL", sl), ("TP", tp)):
        try:
            level = client.post(f"/api/v1/positions/{pos['id']}/tp-sl",
                                {"ty": kind, "p": price, "ep": True})
            print(f"  {kind} set at {level['p']}")
        except FuturesApiError as err:
            # FUT-1301: price already on the wrong side of mark; FUT-1302: SL beyond liquidation
            print(f"  {kind} skipped: {err}")
        time.sleep(PAUSE)
```

{% endcode %}

{% hint style="info" %}
Levels are validated against the current mark price: a `LONG` take-profit must be above it and a stop-loss below it (`FUT-1301`), and a stop-loss must not be beyond the liquidation price (`FUT-1302`). An entire-position level always closes the whole position, whatever its size when it fires.
{% endhint %}

## Related Pages

* [Add TP/SL](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#add-tp-sl)
* [TP/SL model](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#tp-sl-model)
* [Get Open Positions](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#get-open-positions)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/protect-open-positions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
