I created a django view which upon receiving a request (POST method) will open orders on the grid levels

its task is that it should not close the grid orders until the close request is not sent.
now this is the way I want the grids to work.

  1. the entry price should also be counted inn the grid
  2. if the Entry order is ‘buy’, whenever it touches a high level grid price, it should sell (as the levels are already given in the signal. same for the buy if it touches the lower level. the high levels will be called favor levels and lower levels will be called against level
  3. if the entry order is ‘sell’, it should be opposite of the buy. whenever it touches a high level grid price, it should sell (as the levels are already given in the signal. same for the buy if it touches the lower level. the high levels will be called against levels and lower levels will be called favor level.
  4. if one grid level is touched, it should open a opposite order on the previous level. including the entry level.
  5. 1 level should only have 1 order placed until any other level is breached.
    this is my current code which has alot of issues. fix that for me

Issues:
It doesn’t open any order on the previous level when a grid level is breached
if i add to open the order, it executes multiple orders at the same level

It has some unique features than the normmal grid

  1. when the entry order is ‘buy/long’ it will name the high level as ‘favor_levels’ and lower grid levels to ‘against_level’. It same but opposite for the ‘sell/short’ entry order
def monitor_grid_orders(symbol, side, qty, entry_price, favor_levels, against_levels, favor_qty_percentage,
                        against_qty_percentage):
    levels = [entry_price] + favor_levels + against_levels
    levels.sort()
    last_breached_index = -1  # Track the index of the last breached level
    last_price = None

    while True:  # Infinite loop to continuously monitor
        try:
            current_price = bybit.fetch_ticker(symbol)['last']
            print(f"Current price: {current_price}")

            if current_price != last_price:
                for i in range(len(levels)):
                    level = levels[i]
                    if (side.lower() == 'buy' and level <= current_price) or (
                            side.lower() == 'sell' and level >= current_price):
                        if i > last_breached_index:
                            print(f"Level breached: {level}")
                            last_breached_index = i
                            quantity = qty * (favor_qty_percentage / 100) if side.lower() == 'buy' else qty * (
                                        against_qty_percentage / 100)

                            if side.lower() == 'buy':
                                if i == 0:
                                    # Open sell order at entry price
                                    bybit.create_order(symbol, 'limit', 'sell', quantity, entry_price)
                                else:
                                    # Open buy order at the breached level and sell at previous level
                                    bybit.create_order(symbol, 'limit', 'buy', quantity, levels[i])
                                    bybit.create_order(symbol, 'limit', 'sell', quantity, levels[i - 1])
                            else:  # side.lower() == 'sell'
                                if i == 0:
                                    # Open buy order at entry price
                                    bybit.create_order(symbol, 'limit', 'buy', quantity, entry_price)
                                else:
                                    # Open sell order at the breached level and buy at previous level
                                    bybit.create_order(symbol, 'limit', 'sell', quantity, levels[i])
                                    bybit.create_order(symbol, 'limit', 'buy', quantity, levels[i - 1])

                            print('Orders placed.')
                            break  # Exit loop after placing one order per price level

                last_price = current_price

            time.sleep(1.5)

        except Exception as e:
            print(f"Error: {str(e)}")
            time.sleep(1)

@api_view(['POST'])
def open_grid_orders(request):
    if request.method == 'POST':
        data = request.data
        secret = data.get('secret')

        if secret != config.secret:
            return Response({'error': 'Invalid secret'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            order = extract_grid_data(data)
            symbol = order['symbol']
            order_type = order['orderType']
            side = order['side']
            qty = float(order['qty'])
            price = float(order['price'])
            favor_levels = [float(level) for level in order.get('favor_levels', [])]
            against_levels = [float(level) for level in order.get('against_levels', [])]
            percentage_difference_favor = order['percentage_difference_favor']
            percentage_difference_against = order['percentage_difference_against']

            # Open initial order
            bybit.create_order(symbol, order_type, side, qty, price)

            # Open grid orders
            for level in favor_levels:
                level_price = float(level)
                qty_percent = qty * (percentage_difference_favor / 100)

                # Place sell orders at favor levels
                bybit.create_order(symbol, 'limit', 'sell', qty_percent, level_price)

            for level in against_levels:
                level_price = float(level)
                qty_percent = qty * (percentage_difference_against / 100)

                # Place buy orders at against levels
                bybit.create_order(symbol, 'limit', 'buy', qty_percent, level_price)

            # Start monitoring orders in a separate thread
            monitoring_thread = threading.Thread(target=monitor_grid_orders, args=(
                symbol, side, qty, price, favor_levels, against_levels, percentage_difference_favor,
                percentage_difference_against))
            monitoring_thread.start()

            save_order_to_db(order)
            return Response({'success': 'Grid orders created and monitoring started successfully'},
                            status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

I am expecting that it satisfies the above conditions. I tried from chat-gpt which was a mistake obviously and tried myself few changes but none of them works

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật