stop loss is not placed or triggered. otherwise code works properly. its a simple buy sell(futures.). anyone help

import requests
import json
import hashlib
import hmac
from urllib.parse import urlencode
import time
import datetime

Binance API credentials

api_key =
api_secret =

Binance Futures API endpoint URLs

BASE_URL = ‘https://fapi.binance.com
ORDERS_API = ‘/fapi/v1/order’
KLINE_API = ‘/fapi/v1/klines’

Trading parameters

symbol = ‘MATICUSDT’
quantity = 50 # Number of MATIC tokens to market buy
leverage = 5 # Leverage (e.g., 10x)
entry_price = None # Variable to store the entry price of the trade

Define the stop loss percentage

stop_loss_percent = .05 # Change this to your desired stop loss percentage (1% in this example)

Function to generate the API signature

def generate_signature(data):
return hmac.new(api_secret.encode(‘utf-8’), data.encode(‘utf-8’), hashlib.sha256).hexdigest()

Function to place a market buy order

def place_market_buy_order(symbol, quantity, leverage):
order_params = {
‘symbol’: symbol,
‘side’: ‘BUY’,
‘quantity’: quantity,
‘type’: ‘MARKET’,
‘leverage’: leverage
}

# Generate a unique timestamp in milliseconds
timestamp = int(time.time() * 1000)

# Add timestamp to the order parameters
order_params['timestamp'] = timestamp

# Generate the API signature
signature = generate_signature(urlencode(order_params))

# Add the API key and signature to the request headers
headers = {
    'X-MBX-APIKEY': api_key
}

# Send the POST request to place the market sell (short) order
response = requests.post(BASE_URL + ORDERS_API, params={**order_params, 'signature': signature}, headers=headers)

return response.json()

Function to close an existing position (market sell)

def close_position(symbol, quantity):
order_params = {
‘symbol’: symbol,
‘side’: ‘SELL’,
‘quantity’: quantity,
‘type’: ‘MARKET’
}

# Generate a unique timestamp in milliseconds
timestamp = int(time.time() * 1000)

# Add timestamp to the order parameters
order_params['timestamp'] = timestamp

# Generate the API signature
signature = generate_signature(urlencode(order_params))

# Add the API key and signature to the request headers
headers = {
    'X-MBX-APIKEY': api_key
}

# Send the POST request to close the position (market SELL)
response = requests.post(BASE_URL + ORDERS_API, params={**order_params, 'signature': signature}, headers=headers)

return response.json()

Function to get the current price of the symbol

def get_current_price(symbol):
params = {
‘symbol’: symbol,
‘interval’: ‘1m’,
‘limit’: 1
}
response = requests.get(BASE_URL + KLINE_API, params=params)
kline_data = response.json()
if kline_data and len(kline_data) > 0:
return round(float(kline_data[0][4]), 5) # Limit to 5 digits after the decimal point
return None

Set the start time to 22:00:00

start_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

Calculate the current time

current_time = datetime.datetime.now()

Set the end time to 23:00:00

end_time = current_time.replace(hour=1, minute=0, second=0, microsecond=0)

Initialize a flag to alternate between market buy and close position

market_buy_order = True

Initialize the stop loss trigger flag

stop_loss_triggered = False

Loop to place BUY orders and close positions

while current_time < end_time:
if current_time >= start_time:
try:
current_price = get_current_price(symbol)

        if market_buy_order:
            # Place a market buy order
            response = place_market_buy_order(symbol, quantity, leverage)

            # Check the response
            if 'orderId' in response:
                current_time = datetime.datetime.now()
                print(f"Market buy order placed successfully at {current_time}. Order ID: {response['orderId']}")

                # Record the timestamp when the market buy order was placed
                trade_start_time = datetime.datetime.now()
                trade_start_quantity = quantity
                entry_price = current_price

                # Calculate the stop loss price
                stop_loss_price = round(entry_price - (entry_price * (stop_loss_percent / 100.0)), 5)
                print(f"Stop Loss Price: {stop_loss_price}")

            else:
                print(f"Failed to place market buy order. Error: {response}")
        else:
            # Check if a market buy order was placed previously
            if entry_price:
                # Check if the current price falls below the stop loss price
                if current_price <= stop_loss_price:
                    # Close the position as a market sell order
                    response = close_position(symbol, trade_start_quantity)

                    if 'orderId' in response:
                        current_time = datetime.datetime.now()
                        print(f"Market sell order placed successfully at {current_time}. Order ID: {response['orderId']}")

                        # Record the timestamp when the position was closed
                        trade_end_time = datetime.datetime.now()
                        trade_end_quantity = trade_start_quantity
                        exit_price = current_price

                        # Calculate profit or loss for the trade
                        profit_or_loss = (trade_start_quantity) * (exit_price - entry_price)
                        print(f"Trade start time: {trade_start_time}")
                        print(f"Trade end time: {trade_end_time}")
                        print(f"Quantity of orders placed: {trade_start_quantity}")
                        print(f"Quantity of orders closed: {trade_end_quantity}")
                        print(f"Entry Price: {entry_price}")
                        print(f"Exit Price: {exit_price}")
                        print(f"Profit or Loss: {profit_or_loss}")

                        # Reset the stop loss trigger flag
                        stop_loss_triggered = False

                    else:
                        print(f"Failed to close position. Error: {response}")

        # Toggle the flag for the next iteration
        market_buy_order = not market_buy_order

        # Check if the trade duration exceeds 2 minutes
        current_time = datetime.datetime.now()
        if current_time - trade_start_time >= datetime.timedelta(minutes=2):
            # Close the position if it's open and the trade duration exceeds 2 minutes
            if entry_price and not stop_loss_triggered:
                response = close_position(symbol, trade_start_quantity)

                if 'orderId' in response:
                    current_time = datetime.datetime.now()
                    print(f"Market sell order placed successfully at {current_time}. Order ID: {response['orderId']}")

                    # Record the timestamp when the position was closed
                    trade_end_time = datetime.datetime.now()
                    trade_end_quantity = trade_start_quantity
                    exit_price = current_price

                    # Calculate profit or loss for the trade
                    profit_or_loss = (trade_start_quantity) * (exit_price - entry_price)
                    print(f"Trade start time: {trade_start_time}")
                    print(f"Trade end time: {trade_end_time}")
                    print(f"Quantity of orders placed: {trade_start_quantity}")
                    print(f"Quantity of orders closed: {trade_end_quantity}")
                    print(f"Entry Price: {entry_price}")
                    print(f"Exit Price: {exit_price}")
                    print(f"Profit or Loss: {profit_or_loss}")

            # Reset the stop loss trigger flag
            stop_loss_triggered = False

    except Exception as e:
        print(f"Error placing order: {e}")

# Sleep for 2 minutes before checking the time again
time.sleep(120)
current_time = datetime.datetime.now()

please share more details of the question for better understanding.

hi.
the strategy of this code is :
buy the symbol . hold for 2 minutes . then close the position.
sleep for 2 minutes.
repeat till we manuall stop.
im trying to place a stop loss for this code, where it should close the position, when the stop loss is triggered. which doesnt happen. it calculates teh stop loass( which is .1 percent of the entry price). prints the same when the trade is entered. but stop loss is not triggered.