You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bybit API设置追踪止损?

How to Set a Conditional Trailing Stop for Bybit USDT-M LONG Positions

Your requirement—activating a 5% trailing stop only after the position gains 10% from entry—can't be done directly via Bybit's native Set Trading Stop API. Instead, you'll need a two-step workflow: monitor price movement to hit the 10% threshold, then trigger the trailing stop. Below's a practical implementation.

Step 1: Fetch Position & Market Data

First, retrieve your position's entry price and the current market price to track when the 10% gain is hit. Use Bybit's Get Position Info and Market Ticker endpoints.

Example Python Code

import requests
import time
import hmac
import hashlib
import urllib.parse

# Replace with your credentials
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
BASE_URL = "https://api.bybit.com"
SYMBOL = "BTCUSDT"  # Adjust to your contract

def sign_request(params, timestamp):
    query_string = urllib.parse.urlencode(params)
    sign = hmac.new(API_SECRET.encode(), f"{timestamp}{API_KEY}{query_string}".encode(), hashlib.sha256).hexdigest()
    return sign

def get_position_info():
    endpoint = "/v5/position/list"
    timestamp = str(int(time.time() * 1000))
    params = {
        "category": "linear",
        "symbol": SYMBOL
    }
    sign = sign_request(params, timestamp)
    headers = {
        "X-BAPI-API-KEY": API_KEY,
        "X-BAPI-TIMESTAMP": timestamp,
        "X-BAPI-SIGN": sign
    }
    response = requests.get(f"{BASE_URL}{endpoint}", params=params, headers=headers)
    return response.json()

def get_current_price():
    endpoint = "/v5/market/ticker"
    params = {"category": "linear", "symbol": SYMBOL}
    response = requests.get(f"{BASE_URL}{endpoint}", params=params)
    return float(response.json()["result"]["list"][0]["lastPrice"])

Step 2: Monitor & Activate Trailing Stop

Once the current price hits 10% above your entry price, call the Set Trading Stop API to enable the 5% trailing stop.

Example Python Code

def set_trailing_stop(trailing_percent):
    endpoint = "/v5/position/trading-stop"
    timestamp = str(int(time.time() * 1000))
    params = {
        "category": "linear",
        "symbol": SYMBOL,
        "trailingStop": str(trailing_percent),
        "positionIdx": 0  # 0 = one-way mode; use 1 for long in hedge mode
    }
    sign = sign_request(params, timestamp)
    headers = {
        "X-BAPI-API-KEY": API_KEY,
        "X-BAPI-TIMESTAMP": timestamp,
        "X-BAPI-SIGN": sign,
        "Content-Type": "application/json"
    }
    response = requests.post(f"{BASE_URL}{endpoint}", json=params, headers=headers)
    return response.json()

# Main execution flow
position_data = get_position_info()
entry_price = float(position_data["result"]["list"][0]["avgPrice"])
activation_price = entry_price * 1.10  # 10% gain threshold

print(f"Entry price: {entry_price}, Activation threshold: {activation_price}")

while True:
    current_price = get_current_price()
    if current_price >= activation_price:
        print("Threshold hit—activating trailing stop")
        result = set_trailing_stop(5)  # 5% trailing stop
        print(f"API Response: {result}")
        break
    print(f"Current price: {current_price} | Waiting for threshold...")
    time.sleep(10)  # Check every 10 seconds (adjust as needed)

Key Details & Troubleshooting

  • Signature Logic: The sign_request function handles Bybit's required request signing—don't skip this, or authenticated endpoints will reject your calls.
  • Position Mode: Adjust positionIdx if using hedge mode (1 for long positions, 2 for short).
  • Trailing Stop Behavior: For LONG positions, a trailingStop value of 5 means the stop price will trail 5% below the highest price reached after activation. If the price drops 5% from that peak, the stop triggers.
  • Permissions: Ensure your API key has "Trade" enabled in Bybit's API settings.
  • Error Handling: Add try-except blocks to handle network issues, API errors, or cases where the position is closed before activation.

内容的提问来源于stack exchange,提问作者Mehmet Emin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:23:33