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 at5%from the entry price, on the right side forLONGandSHORT.Adds one entire-position
SLand oneTPlevel per position.Skips a level the API refuses, for example when the price has already moved past it.
Start with Setup & Helpers if you still need the shared prerequisites.
#!/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)Related Pages
Add TP/SL
TP/SL model
Get Open Positions
Was this helpful?

