> 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/open-a-position-with-tp-sl.md).

# Open a Position with TP/SL

Open a market LONG sized by spend, with take-profit and stop-loss attached.

Use this script to open a position and protect it in one request.

## What This Script Does

* Checks the pair is open for trading and the leverage is within its range.
* Checks the spend against your minimum order amount.
* Reads the current mark price.
* Places a `MARKET` `OPEN_LONG` for `$50` of spend at `10x` `ISOLATED`, with take-profit `+3%` and stop-loss `−2%` from the mark price.
* Prints the fill and the resulting position with its TP/SL levels.

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

{% code title="open\_with\_tpsl.py" %}

```python
#!/usr/bin/env python3
"""Open a market LONG with a fixed spend and attach take-profit and stop-loss."""
import asyncio
from decimal import Decimal

from futures_helpers import FuturesClient, FuturesApiError, get_pairs, mark_price, round_price

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

SYMBOL = "BTCUSDT"
SPEND = Decimal("50")         # USD: initial margin + opening fee, at most
LEVERAGE = Decimal("10")      # ISOLATED leverage, within the pair's mnl–ml
TP_PCT = Decimal("0.03")      # take profit 3% above the mark price
SL_PCT = Decimal("0.02")      # stop loss 2% below the mark price

client = FuturesClient(API_KEY, API_SECRET)

# Step 1 — Pair rules
pair = get_pairs()[SYMBOL]
if pair["st"] != "active":
    raise SystemExit(f"{SYMBOL} is {pair['st']}: opening is not allowed now")
if not pair["mnl"] <= LEVERAGE <= pair["ml"]:
    raise SystemExit(f"leverage must be within {pair['mnl']}–{pair['ml']}")

# Step 2 — Your order-amount limits for this pair
limits = client.get("/api/v1/trade/account")["lim"][str(pair["gid"])]
if limits["mn"] is not None and SPEND < Decimal(limits["mn"]):
    raise SystemExit(f"spend is below the minimum order amount {limits['mn']} USD")

# Step 3 — TP/SL from the current mark price
mark = asyncio.run(mark_price(pair["gid"]))
tp = round_price(mark * (1 + TP_PCT), pair["ts"])
sl = round_price(mark * (1 - SL_PCT), pair["ts"])
print(f"{SYMBOL} mark {mark}  →  TP {tp}  SL {sl}")

# Step 4 — Market order sized by spend, with attached TP/SL
try:
    order = client.post("/api/v1/orders", {
        "pi": pair["gid"],
        "d": "OPEN_LONG",
        "ty": "MARKET",
        "s": SPEND,
        "l": LEVERAGE,
        "mm": "ISOLATED",
        "tp": tp,
        "sl": sl,
    })
except FuturesApiError as err:
    raise SystemExit(f"order rejected: {err}")

print(f"filled {order['fq']} {pair['bc']} @ {order['afp']}, fee {order['f']}")

# Step 5 — The resulting position
for pos in client.get("/api/v1/positions", params={"pairId": pair["gid"]}):
    if pos["id"] == order["po"]:
        levels = ", ".join(f"{lvl['ty']} {lvl['p']}" for lvl in pos["tpsl"]) or "none"
        print(f"position {pos['id']}: {pos['s']} {pos['sz']} @ {pos['e']}, "
              f"margin {pos['im']}, liq {pos['lq']}, levels: {levels}")
```

{% endcode %}

{% hint style="info" %}
`s` (spend) caps initial margin plus opening fee, so the filled size is whatever fits into `$50` at the fill price. Use `q` instead for an exact size in the base coin. An attached TP/SL that is invalid at the fill price rejects the whole order.
{% endhint %}

## Related Pages

* [Place Order](broken://pages/2d7e1d40d8e19f9de1a0ebe485fd2e9a598d0b28#place-order)
* [Get Open Positions](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#get-open-positions)
* [Get Account Trading Settings](broken://pages/c11c05c7f6ca1d74125204977652ac67c6f93c25#get-account-trading-settings)
* [Mark Price](broken://pages/20792fac94e50747f3b7d86c2541e7bc1c64a9e2)


---

# 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/open-a-position-with-tp-sl.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.
