For the complete documentation index, see llms.txt. This page is also available as Markdown.

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 if you still need the shared prerequisites.

open_with_tpsl.py
#!/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}")

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.

  • Place Order

  • Get Open Positions

  • Get Account Trading Settings

  • Mark Price

Was this helpful?