How to place stop loss & trailing stop loss order if stoploss is 50 points and stoploss traill if price move up upward direction 100 points then stop loss traill 30 points?

Delta Exchange API Base URL

BASE_URL = “https://api.india.delta.exchange

Function to fetch historical OHLC data from Delta Exchange

def fetch_historical_prices(symbol=“BTCUSD”, resolution=“1m”, limit=200):
url = f"{BASE_URL}/v2/history/candles"

end_time = int(time.time())  # Current time in UNIX timestamp
start_time = end_time - (limit * 60)  # Fetch last 'limit' number of 1-minute candles

params = {
    "symbol": symbol,
    "resolution": resolution,  
    "start": start_time,
    "end": end_time
}

headers = {
    'api-key': api_key  # API Key for authentication
}

try:
    response = requests.get(url, params=params, headers=headers)
    data = response.json()

    if response.status_code == 200 and 'result' in data and isinstance(data['result'], list):
        df = pd.DataFrame(data['result'])
        if not df.empty:
            df = df.sort_values(by="time")  # Sort by timestamp
            df[['open', 'high', 'low', 'close']] = df[['open', 'high', 'low', 'close']].astype(float)
            return df
    else:
        print(f"API Error: {data}")
        return None

except requests.exceptions.RequestException as e:
    print(f"API Request Failed: {e}")
    return None

Function to calculate RSI using TA-Lib

def calculate_rsi(prices, period=14):
if len(prices) < period:
return None # Not enough data to calculate RSI

prices = np.array(prices, dtype=np.float64)  # Ensure correct data type
rsi = talib.RSI(prices, timeperiod=period)

if np.isnan(rsi[-1]):  # Ensure valid RSI value
    return None
return rsi[-1]

Generate API signature

def generate_signature(method, endpoint, payload):
timestamp = str(int(time.time()))
signature_data = method + timestamp + endpoint + payload
message = bytes(signature_data, ‘utf-8’)
secret = bytes(api_secret, ‘utf-8’)
hash = hmac.new(secret, message, hashlib.sha256)
return hash.hexdigest(), timestamp

Trading Logic: Wait until RSI crosses above 60

while True:
df = fetch_historical_prices()

if df is not None and len(df) > 14:  # Ensure enough data for RSI calculation
    rsi_value = calculate_rsi(df['close'].tolist())
    latest_candle = df.iloc[-1]  # Get the latest candle
    
    print(f"\nLatest Candle: Time: {latest_candle['time']}, Open: {latest_candle['open']}, High: {latest_candle['high']}, Low: {latest_candle['low']}, Close: {latest_candle['close']}")
    print(f"Current RSI: {rsi_value}")

    if rsi_value is not None and rsi_value > 60:
        print("\n✅ RSI is above 60, placing a BUY order...")

        # Prepare order data
        order_data = {
            'product_id': 27,  # BTCUSD product ID (change if needed)
            'size': 1,
            'order_type': 'market_order',
            'side': 'buy'
        }

        body = json.dumps(order_data, separators=(',', ':'))
        method = 'POST'
        endpoint = '/v2/orders'

        signature, timestamp = generate_signature(method, endpoint, body)

        # API headers for order placement
        headers = {
            'api-key': api_key,
            'signature': signature,
            'timestamp': timestamp,
            'Content-Type': 'application/json'
        }

        # Send buy order
        try:
            response = requests.post(f"{BASE_URL}/v2/orders", headers=headers, json=order_data)
            order_response = response.json()

            print("\n🚀 Order Placed Successfully:", order_response)
            break  # Exit loop after successful buy order
        except requests.exceptions.RequestException as e:
            print(f"⚠️ Order API Request Failed: {e}")

    else:
        print("⏳ RSI is below 60. Retrying in 60 seconds...")
        time.sleep(30)  # Wait before checking again

else:
    print("⚠️ Failed to fetch historical BTCUSD price data. Retrying in 60 seconds...")
    time.sleep(30)  # Wait before retrying

HI @suvendu , you want to set an initial SL of 50 points and with every 100 points price move onside the trade you want to trail the SL by 30 points.

Initially set the SL 50 points below entry. then you would need a continuous counter called “highest_price” to keep track of the highest price reached. keep checking for recent price and updating highest_price. once price gets increased by 100 , shift SL 30 points up. ensure new SL is only adjusted above. if SL is updated , modify the order with the new SL.

sharing the core logic here

trailing_stop_loss = entry_price - 50
highest_price = entry_price

while True:
        time.sleep(5) 
        latest_price = fetch_latest_price()

        if latest_price > highest_price:
            highest_price = latest_price

            if highest_price >= entry_price + 100:
               new_stop_loss = highest_price - 30 

               if new_stop_loss > trailing_stop_loss:
                  trailing_stop_loss = new_stop_loss
                  modify_stop_loss(order_id, trailing_stop_loss)

make sure you fetch entry_price at order placement

to implement placing orders for above, you can leverage our DeltaRestClient library where you can necessary order placing functions that you can call. (GitHub - delta-exchange/python-rest-client)

Also take a look at our api docs section for orders management. Delta Exchange Api

STOPLOSS ORDER NOT RESPONSE , I GIVE U CODE BELOW

       # Delta Exchange API Base URL

BASE_URL = “https://api.india.delta.exchange

Function to fetch historical OHLC data from Delta Exchange

def fetch_historical_prices(symbol=“BTCUSD”, resolution=“1m”, limit=200):
url = f"{BASE_URL}/v2/history/candles"

end_time = int(time.time())  # Current time in UNIX timestamp
start_time = end_time - (limit * 60)  # Fetch last 'limit' number of 1-minute candles

params = {
    "symbol": symbol,
    "resolution": resolution,  
    "start": start_time,
    "end": end_time
}

headers = {
    'api-key': api_key  # API Key for authentication
}

try:
    response = requests.get(url, params=params, headers=headers)
    data = response.json()

    if response.status_code == 200 and 'result' in data and isinstance(data['result'], list):
        df = pd.DataFrame(data['result'])
        if not df.empty:
            df = df.sort_values(by="time")  # Sort by timestamp
            df[['open', 'high', 'low', 'close']] = df[['open', 'high', 'low', 'close']].astype(float)
            return df
    else:
        print(f"API Error: {data}")
        return None

except requests.exceptions.RequestException as e:
    print(f"API Request Failed: {e}")
    return None

Function to calculate RSI using TA-Lib

def calculate_rsi(prices, period=14):
if len(prices) < period:
return None # Not enough data to calculate RSI

prices = np.array(prices, dtype=np.float64)  # Ensure correct data type
rsi = talib.RSI(prices, timeperiod=period)

if np.isnan(rsi[-1]):  # Ensure valid RSI value
    return None
return rsi[-1]

Generate API signature

def generate_signature(method, endpoint, payload):
timestamp = str(int(time.time()))
signature_data = method + timestamp + endpoint + payload
message = bytes(signature_data, ‘utf-8’)
secret = bytes(api_secret, ‘utf-8’)
hash = hmac.new(secret, message, hashlib.sha256)
return hash.hexdigest(), timestamp

Trading Logic: Wait until RSI crosses above 60

while True:
df = fetch_historical_prices()

if df is not None and len(df) > 14:  # Ensure enough data for RSI calculation
    rsi_value = calculate_rsi(df['close'].tolist())
    latest_candle = df.iloc[-1]  # Get the latest candle
    
    print(f"\nLatest Candle: Time: {latest_candle['time']}, Open: {latest_candle['open']}, High: {latest_candle['high']}, Low: {latest_candle['low']}, Close: {latest_candle['close']}")
    print(f"Current RSI: {rsi_value}")

    if rsi_value is not None and rsi_value > 40:
        print("\n✅ RSI is above 60, placing a BUY order...")

        # Prepare order data for Buy
        order_data = {
            'product_id': 27,  # BTCUSD product ID (change if needed)
            'size': 1,
            'order_type': 'market_order',
            'side': 'buy'
        }

        body = json.dumps(order_data)
        method = 'POST'
        endpoint = '/v2/orders'

        signature, timestamp = generate_signature(method, endpoint, body)

        # API headers for order placement
        headers = {
            'api-key': api_key,
            'signature': signature,
            'timestamp': timestamp,
            'Content-Type': 'application/json'
        }

        # Send buy order
        try:
            response = requests.post(f"{BASE_URL}/v2/orders", headers=headers, json=order_data)
            order_response = response.json()

            if response.status_code == 200:
                print("\n🚀 Order Placed Successfully:", order_response)
                buy_price = order_response.get('avg_fill_price', 0)  # Get the average fill price for the buy order
                
                # Set Stop Loss (200 below the buy price)
                stop_loss_price = buy_price - 200  # Fixed Stop loss of 200
                print(f"Setting stop loss at {stop_loss_price}...")

                stop_loss_order = {
                    'product_id': 27,  # BTCUSD product ID
                    'size': 1,
                    'side': 'sell',
                    'order_type': 'market',
                    'stop_price': stop_loss_price
                }

                # Send stop loss order
                response = requests.post(f"{BASE_URL}/v2/orders", headers=headers, json=stop_loss_order)
                stop_loss_response = response.json()
                print("Stop loss order response:", stop_loss_response)

                # Set Trailing Stop Loss (trail amount of 20)
                trail_amount = 20
                trail_stop_order = {
                    'product_id': 27,  # BTCUSD product ID
                    'size': 1,
                    'side': 'sell',
                    'order_type': 'limit',  # Using limit for trailing stop
                    'trail_amount': trail_amount,
                    'isTrailingStopLoss': True
                }

                # Send trailing stop order
                response = requests.post(f"{BASE_URL}/v2/orders", headers=headers, json=trail_stop_order)
                trail_stop_response = response.json()
                print("Trailing stop order response:", trail_stop_response)

                break  # Exit loop after placing buy, stop loss, and trailing stop orders

            else:
                print(f"⚠️ Order API Request Failed: {order_response}")
        except requests.exceptions.RequestException as e:
            print(f"⚠️ Order API Request Failed: {e}")

    else:
        print("⏳ RSI is below 60. Retrying in 60 seconds...")
        time.sleep(30)  # Wait before checking again

else:
    print("⚠️ Failed to fetch historical BTCUSD price data. Retrying in 60 seconds...")
    time.sleep(30)  # Wait before retrying

Order Placed Successfully: {‘meta’: {}, ‘result’: {‘product_id’: 27, ‘limit_price’: ‘93150.5’, ‘stop_trigger_method’: None, ‘cancellation_reason’: None, ‘bracket_stop_loss_price’: None, ‘bracket_take_profit_price’: None, ‘updated_at’: ‘2025-03-06T18:17:02.885608Z’, ‘side’: ‘buy’, ‘state’: ‘closed’, ‘id’: 324613847, ‘average_fill_price’: ‘88716.5’, ‘reduce_only’: False, ‘paid_commission’: ‘0.05234274’, ‘close_on_trigger’: ‘false’, ‘stop_price’: None, ‘order_type’: ‘market_order’, ‘trail_amount’: None, ‘created_at’: ‘2025-03-06T18:17:02.399341Z’, ‘time_in_force’: ‘ioc’, ‘client_order_id’: None, ‘user_id’: 99206279, ‘bracket_order’: None, ‘bracket_take_profit_limit_price’: None, ‘bracket_stop_loss_limit_price’: None, ‘commission’: ‘0’, ‘quote_size’: None, ‘size’: 1, ‘bracket_trail_amount’: None, ‘meta_data’: {‘cashflow’: ‘0’, ‘ip’: ‘45.112.243.33’, ‘otc’: False, ‘pnl’: ‘0’, ‘source’: ‘api’}, ‘product_symbol’: ‘BTCUSD’, ‘stop_order_type’: None, ‘mmp’: ‘disabled’, ‘unfilled_size’: 0}, ‘success’: True}
Setting stop loss at -200…
Stop loss order response: {‘error’: {‘code’: ‘Signature Mismatch’, ‘context’: {‘signature_data’: ‘POST1741285021/v2/orders{“product_id”: 27, “size”: 1, “side”: “sell”, “order_type”: “market”, “stop_price”: -200}’}}, ‘success’: False}
Trailing stop order response: {‘error’: {‘code’: ‘Signature Mismatch’, ‘context’: {‘signature_data’: ‘POST1741285021/v2/orders{“product_id”: 27, “size”: 1, “side”: “sell”, “order_type”: “limit”, “trail_amount”: 20, “isTrailingStopLoss”: true}’}}, ‘success’: False}

Hi @suvendu , you are passing stop_price”: -200 , which is incorrect. Stop-loss should be set relative to the current market price. calculate the correct stop price dynamically. stop_price = latest_price - 200

isTrailingStopLoss”: true is not required in the request.

let me know if you face any further issuese.

i can’t do this ,let me know for assist!!!

Hi @suvendu , for further assistance, pls book a 1-1 google meet here with me. Calendly